[undefined]和[,]之间的区别是什么?
可能重复:
What is “undefined x 1” in JavaScript? [undefined]和[,]之间的区别是什么?
在铬21,喂养[,]
到控制台输出
[未定义X 1]
和馈送[undefined]
输出
[未定义]
是什么[undefined]
和[undefined x 1]
之间的差异?
什么是符号[undefined x 1]
?
[,]
是sparse array。它的长度为1
,但没有值(0 in [,] === false
)。它也可以写成new Array(1)
。
[undefined]
是长度为1
的数组,其值为undefined
,索引号为0
。
访问属性“0
”时,两者都会返回undefined
- 第一个因为该属性未定义,第二个因为值为“未定义”。但是,阵列不同,它们的output in the console也是不同的。
看起来它只是显示重复'未定义'值的简写方式。例如:
> [,,,]
[ undefined x 3 ]
但[]
是不一样的[undefined]
可言。如果我是你,我会仔细检查一下。
请重新阅读我的问题。我问'','',而不是'[]'。 – Randomblue 2012-08-04 13:17:59
pimvdb的编辑说明:http://es5.github.com/#x11.1.4,“如果一个元素在数组末尾消失,那么该元素不会影响数组的长度。” – 2012-08-04 13:20:55
@Randomblue很好,因为你编辑它..: - \ – nickf 2012-08-04 13:43:49
那奇[]
输出只是[]
再次为我在Chrome 21
反正[a, b, c, ...]
是的JavaScript数组符号,所以你基本上是定义没有值的数组。
然而结尾,
是可以接受的,使数组产生更容易。那么Chrome告诉你的是阵列中有一个未定义的值。查看代码示例。
[,,]
> [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]
[,]
创建长度为1且没有索引的数组。
[undefined]
创建长度为1的数组,undefined
值为索引0
。
Chrome的undefined × x
是稀疏数组没有循序索引:
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`
如果你是一个稀疏阵列上使用.forEach
,它跳过不存在的指标。
a.forEach(function() {
console.log(true); //Only logs one true even though the array's length is 9
});
哪里,如果你做一个正常的.length
基于循环:
for (var i = 0; i < a.length; ++i) {
console.log(true); //will of course log 9 times because it's only .length based
}
有一种疑难杂症,如果你希望.forEach
有同样的表现非标准实现。
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
});
我相信,你需要阅读此[链接](http://stackoverflow.com/questions/10683773/what-is-undefined-x-1-in-javascript) – 2012-08-04 13:15:28
'[]'变我'[]'... – pimvdb 2012-08-04 13:15:58
控制台输出不是数据,它不是*(必然)* JavaScript表示法或语法。这是控制台开发人员认为应该看起来的数据的可视化表示。有时这很有帮助,有时可能会造成混淆或误导。 – 2012-08-04 13:21:21