-3

Array(3), result:

{ length: 3__proto__: Array(0) }

There is no index 0, 1, 2...

But Array.call(null, Array(3)) has,

{ 0: undefined, 1: undefined, 2: undefined, length: 3, __proto__: Array(0) }

I know I can get indexs by Array.from or Array.fill.

I just want to know why Array.call(null, Array(3)) can produce the indexs. I want to know the inner logic of Array.call(null, Array(3)), What does it exactly do ?

Could anyone explain why?

Lumaskcete
  • 670
  • 6
  • 12
  • `Array(3).fill()` is too hard because why? – Patrick Roberts May 09 '18 at 02:48
  • `Why Array(5) don't have index 0, 1, 2, 3?` it doesn't have index 4 either - just sayin :p - what you want to look for in documentation is *sparse array* – Jaromanda X May 09 '18 at 02:51
  • @31 no, it's no duplicate, I know Array and new Array is the same, I want to know why Array()/new Array() don't have index, comparing to Array.call(). – Lumaskcete May 09 '18 at 04:02
  • @PatrickRoberts, I know Array.fill can make it. I just want to know if any other ways to create array with index without it. – Lumaskcete May 09 '18 at 04:04

2 Answers2

0

Actually,You can use Array.from to transform the array, like this

Array.from(Array(3),(val,index)=>index)
// [0, 1, 2]
Jack Chen
  • 624
  • 5
  • 14
0

Array.length is read and writable. Setting the internal length reference doesn't automatically create empty values. By instaniating an array Array(5) you're setting the internal length, but creating a blank array. If you were to push a value in its index would be 6 but the array would still only contain one item.

Run these too examples in a console. They're equivalent.

let a = Array(5)
a.push('foo') // length 6
a.push('bar') // length 7
a // [empty × 5, "foo", "bar"]

let b = []
b.length = 5
b.push('foo') // length 6
b.push('bar') // length 7
b // [empty × 5, "foo", "bar"]

a.forEach(i => console.log(i))
// foo
// bar

Using Array.call(null, 5) produces the same result as above. Its essentially calling Array(5) with a context of null; Array.call(null, Array(3)) is creating a nested array, with the first value being an array set to length 3.

There is a shortish hand way described in this answer Create a JavaScript array containing 1...N

var N = 10; 
Array.apply(null, {length: N}).map(Number.call, Number)
Lex
  • 4,749
  • 3
  • 45
  • 66