Why can't for-in access the array elements of an empty array?

I want to assign values to an array, but why can"t for-in access the array elements of an empty array?

var arr=new Array(2);
for(var i in arr){
    arr[i]=10;
}
Nov.16,2021

The vacancy in the

array means that there is no value at a certain position in the array. For example, the array returned by the Array constructor is empty.

Array(3) // [, , ,]

, Array (3) in the code above) returns an array with three empty spaces.
Note that the vacancy is not undefined,. The value of a position equal to undefined, is still valuable. Spaces have no value, as can be illustrated by the in operator.

0 in [undefined, undefined, undefined] // true
0 in [, , ,] // false

the above code shows that the 0 position of the first array has a value, and the 0 position of the second array has no value.

ES5's handling of vacancies is already very inconsistent, and vacancies are ignored in most cases.

  • both forEach (), filter (), reduce (), every () and some () skip empty seats.
  • map () skips spaces, but retains this value
  • join () and toString () treat vacancies as undefined, and undefined and null are treated as empty strings.
// forEach
[,'a'].forEach((x,i) => console.log(i)); // 1

// filter
['a',,'b'].filter(x => true) // ['a','b']

// every
[,'a'].every(x => x==='a') // true

// reduce
[1,,2].reduce((x,y) => x+y) // 3

// some
[,'a'].some(x => x !== 'a') // false

// map
[,'a'].map(x => 1) // [,1]

// join
[,'a',undefined,null].join('-sharp') // "-sharpa-sharp-sharp"

// toString
[,'a',undefined,null].toString() // ",a,,"

ES6 explicitly converts the vacancy to undefined.


The

for-in statement can traverse the enumerable properties of the object itself and its prototype chain .
here you need to know the attribute descriptor of the object.
the array items (sparse array items) generated through Array (num) cannot be traversed naturally without initializing the generation of the attribute descriptor .

var arr = new Array(2);
Object.getOwnPropertyDescriptor(arr, '0'); // undefined

Object.getOwnPropertyDescriptor(arr, 'length')
// {value: 2, writable: true, enumerable: false, configurable: false}

is faulty.
for.in loop only traverses enumerable properties


because for in traverses the object's key, empty array is

without key
  

for in can only traverse enumerable attributes and exist values, and undefined is equivalent to no value.

Menu