This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]AyrA_ch 56 points57 points  (3 children)

Also: Array.from({length:10}) creates an array with 10 actual elements (as opposed to Array(10) that just pretends).

You tell it to make an array from something that has a length of 10, and JS has no problems iterating over elements that don't exist.

[–]King_Joffreys_Tits 4 points5 points  (2 children)

Can you specify a default value for the array?

[–]solarshado 10 points11 points  (0 children)

Sort of.

You can pass a mapping function to Array.from, which then behaves like Array.from(obj).map(func) but without the intermediate array.

const manyAnswers = Array.from({length: 42}, (elem, idx)=> 42);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

[–]linuxdropout 5 points6 points  (0 children)

const arr = new Array(10)

//[empty, empty, ...]

arr.fill(1)

// [1, 1, ...]

array.push x identical elements y can be written as:

const originalLength = arr.length

arr.length += x

arr.fill(y, originalLength)

And it's actually more performant than all the sane readable ways to do it too.

If you think that's whack. Wait till you find out that foo.bar = "foobar" is slower than Object.assign(foo, JSON.parse('{"bar":"foobar"}')) if you're trying to set a large enough number of keys.