What is the difference between [undefined] and [,]? [duplicate]

二次信任 提交于 2019-12-17 13:55:34

问题


Possible Duplicate:
What is “undefined x 1” in JavaScript?

In Chrome 21, feeding [,] to the console outputs

[undefined x 1]

and feeding [undefined] outputs

[undefined]

What is the difference between [undefined] and [undefined x 1]?

What is the notation [undefined x 1]?


回答1:


[,] is a sparse array. It has a length of 1, but no values (0 in [,] === false). It can also be written as new Array(1).

[undefined] is an array of length 1 with the value undefined at index 0.

When accessing the property "0", both will return undefined - the first because that property is not defined, the second because the value is "undefined". However, the arrays are different, and so is their output in the console.




回答2:


[,] creates an array with length of 1 and no indices.

[undefined] creates an array with length of 1 with undefined value at index 0.

Chrome's undefined × x is for sparse arrays that don't have sequential indices:

var a = [];

a[8] = void 0; //set the 8th index to undefined, this will make the array's length to be 9 as specified. The array is sparse
console.log(a) //Logs undefined × 8, undefined, which means there are 8 missing indices and then a value `undefined`

If you were to use .forEach on a sparse array, it skips the indices that don't exist.

a.forEach(function() {
    console.log(true); //Only logs one true even though the array's length is 9
});

Where as if you do a normal .length based loop:

for (var i = 0; i < a.length; ++i) {
    console.log(true); //will of course log 9 times because it's only .length based
}

There is a gotcha if you expect .forEach to behave the same as non-standard implementations.

new Array(50).forEach( function() {
    //Not called, the array doesn't have any indices
});

$.each( new Array(50), function() {
    //Typical custom implementation calls this 50 times
});



回答3:


Thats odd [] outputs just [] again for me on Chrome 21.

Anyway [a, b, c, ...] is the array notation of Javascript so you are basically defining an array with no values.

However an ending , is acceptable to make array generation easier. So what Chrome is telling you is there is one undefined value in the array. See code for examples.

[,,]
> [undefined x2]
[1,2,]
> [1, 2]
[1,2,,]
> [1, 2, undefined × 1]
[1,2,,,]
> [1, 2, undefined × 2]
[1,2,,3,4,,,6]
> [1, 2, undefined × 1, 3, 4, undefined × 2, 6]



回答4:


It looks like it's just a shorthand way to display the repeated 'undefined' values. eg:

> [,,,]
  [ undefined x 3 ]

But [] is not the same as [undefined] at all. I'd double check that if I were you.



来源:https://stackoverflow.com/questions/11808946/what-is-the-difference-between-undefined-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!