javascript - Why is the undefined array in js not traversed?
PHP中文网
PHP中文网 2017-07-05 10:50:19
0
4
946

The problem description is not comprehensive

My problem is that when my array is defined as follows:

let a = [undefined, undefined]

a[9] = 1

console.log(a)                //[undefined, undefined, undefined × 7, 1]

Is there any difference between the automatically generated undefined here and the one I defined?

Why can’t I traverse them when I use the built-in traversal?

a.forEach(it => console.log(it))    // 也只会有三个结果
PHP中文网
PHP中文网

认证0级讲师

reply all(4)
某草草

Because what you define is a sparse array (sparse array, the array length is larger than the number of array elements). You can use in to detect whether its array elements exist:

'0' in a  // true,索引存在.
'1' in a  // true
'2' in a  // false,索引不存在
'9' in a  // true

And forEach will only traverse the elements where the original index exists.

过去多啦不再A梦

Is there any difference between the automatically generated undefined here and the one I defined?

This is a trap of arrays, this undefined is not that undefined. The automatically generated ones are called "empty slots", and chrome just shows them as undefined. You can also see that the real undefined is output one by one, and the empty slots output the words "undefined × 7".

forEach, map and the like will skip empty slots. Please refer to the solution

console.log(Array.from(a))
淡淡烟草味

Because forEach is written like this, the built-in forEach will continue when it encounters undefined
You can write a non-skipping version yourself

漂亮男人

You can think about this problem from another angle:
var a = [1,2,3,4]
delete a[0]
console.log(a)//[undefined × 1, 2, 3, 4]
a.length//4
a.forEach(it=>console.log(it))// 2 3 4
Back to the question, when forEach is encapsulated, this "undefined" will be skipped, you can rewrite it Try this method, no matter what the value is, it should be able to be printed normally

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!