Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS creating an array of 3 elements containing random number from 0 to 255 (included) in single line of code

Tags:

javascript

I'm trying to create an array with 3 elements without using for loops, so the code will be a single line (or single statement). What I want to do is creating an array of 3 elements and each element should be random number from 0 to 255 (0 and 255 will be included).

let colors = new Array(3).map((v) => Math.floor(Math.random()*256));

But this code doesn't work, I guess it's because each element is undefined and .map array property can't map undefined elements. What's your suggestions?

like image 802
Muhammed Çağlar TUFAN Avatar asked Dec 17 '22 11:12

Muhammed Çağlar TUFAN


2 Answers

Array.from() is something you are looking for:

const res = Array.from({length: 3}, _ => Math.floor(Math.random()*256))
console.log(res)
like image 115
ulou Avatar answered Feb 02 '23 00:02

ulou


You can try using Array.from() specifying the array-like objects (objects with a length property and indexed elements) of the array as first parameter and the arrow function to fill the array with random values in that range as the second parameter:

let colors = Array.from({length: 3}, () => Math.floor(Math.random() * 256));
console.log(colors);
like image 23
Mamun Avatar answered Feb 01 '23 22:02

Mamun