EN
TypeScript - generate array with 10 random numbers
0 points
In this article, we would like to show you how to generate an array with 10 random numbers in TypeScript.
Quick solution:
xxxxxxxxxx
1
const array: number[] = Array(10) // array size is 10
2
.fill(undefined)
3
.map(() => 50 * Math.random()); // numbers from 0-50 (exclusive)
4
5
console.log(array);
Note:
Use
Math.floor()
to get integers instead of float numbers. You can find practical examples in the sections below.
In this example we take the following steps:
- Create an array with size
10
, - Use
fill()
method to fill thearray
with specified values, - use
map()
method to callMath.random()
to generate a random value for each element in thearray
(from 0-50 exclusive).
Practical example:
xxxxxxxxxx
1
const array: number[] = Array(10) // array size is 10
2
.fill(undefined)
3
.map(() => 50 * Math.random()); // numbers from 0-50 (exclusive)
4
5
console.log(array);
If you want to receive integers instead of float numbers use Math.floor()
method:
Practical example:
xxxxxxxxxx
1
const array: number[] = Array(10) // array size is 10
2
.fill(undefined)
3
.map(() => Math.floor(50 * Math.random())); // numbers from 0-50 (exclusive)
4
5
console.log(array);