[未定义] 和 [,] 有什么区别
What is the difference between [undefined] and [,]?
可能的重复项:
JavaScript 中的"undefined x 1"是什么?
在 Chrome 21 中,[,]
馈送到控制台输出
[未定义 x 1]
和馈送[undefined]
输出
[未定义]
[undefined]
和[undefined x 1]
有什么区别?
什么是符号[undefined x 1]
?
[,]
是一个稀疏数组。它的长度为1
,但没有值(0 in [,] === false
(。它也可以写成new Array(1)
。
[undefined]
是一个长度1
数组,其值undefined
在索引 0
处。
当访问属性" 0
"时,两者都将返回undefined
- 第一个是因为该属性未定义,第二个是因为值是"未定义的"。但是,数组是不同的,它们在控制台中的输出也是如此。
[,]
创建一个长度为 1 且没有索引的数组。
[undefined]
创建一个长度为 1 的数组,其值位于索引 0
处undefined
。
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
});
很奇怪[]
在 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]
看起来这只是显示重复的"未定义"值的简写方法。 例如:
> [,,,]
[ undefined x 3 ]
但[]
与[undefined]
完全不同。如果我是你,我会仔细检查一下。
- 全局变量和全局对象的属性之间有什么区别吗
- 在ember/handlers中使用value和valueBinding有什么区别
- 这两个关于 JavaScript 作用域链的例子有什么区别?
- Math.min()和Math.max()之间有什么区别?在Javascript中
- angularjs中的ng网格和ui网格有什么区别
- webpack开发模式和生产构建模式之间有什么区别
- 缓存!saveLocations()和addLocation()函数有什么区别
- 关于承诺/A+规范,术语“当时可”和“承诺”之间有什么区别
- 以下两者在javascript中有什么区别
- jquery.js和jquery.lite.js有什么区别
- 通过Nuget安装Angular JS和Angular JS核心有什么区别
- XMLHttpRequest对象的open()和send()方法之间有什么区别
- 这两种不同的创建对象文字的方法有什么区别
- jQuery中这两个词有什么区别
- 在Javascript语法中:和::和:::有什么区别
- getElementById 和 getElementsByClassName 有什么区别?
- (typeof variable === “function”) 和 jQuery.isFunction() 有什么区别
- 在使用JS的Ajax调用中,ajaxComplete和beforesend之间有什么区别
- $(e.target).find和template.find('input').value之间有什么区别
- 在javascript中,在变量名之前使用var有什么区别/优势吗