在Chrome 21中,[,]输入控制台输出
[undefined x 1]
并提供[undefined]输出
[未定义]
[undefined]和之间有什么区别[undefined x 1]?
符号是什么[undefined x 1]?
[,] 创建一个长度为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`
Run Code Online (Sandbox Code Playgroud)
如果您要.forEach在稀疏数组上使用它,它会跳过不存在的索引.
a.forEach(function() {
console.log(true); //Only logs one true even though the array's length is 9
});
Run Code Online (Sandbox Code Playgroud)
就像你做一个.length基于正常的循环一样:
for (var i = 0; i < a.length; ++i) {
console.log(true); //will of course log 9 times because it's only .length based
}
Run Code Online (Sandbox Code Playgroud)
如果您希望.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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
293 次 |
| 最近记录: |