forEach 的奇怪数组构造函数行为
Strange array constructor behavior with forEach
我在我的网站上工作时不小心发现了以下数组行为,我真的无法理解。
如果我在我的脚本中写这样的东西:
Array(4).forEach(function(elem) {console.log(elem);});
我return 没有日志条目,或任何与此相关的内容。
相反,如果我这样写:
[undefined,undefined,undefined,undefined].forEach(function(elem) {console.log(elem);});
我确实得到了 4 个日志条目。
我的问题是,这是为什么呢?为什么我不获取数组构造函数的日志条目,而是使用 []
获取它们? constructor specification nor the forEach
specification 都没有真正避开 undefined
或帮助我理解这一点。
forEach()
executes the provided callback once for each element present in the array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined.
您初始化数组的方式确实设置了它的长度,但没有将数组中的值设置为任何值,因此 forEach
不会迭代这些元素:
If the argument len
is a Number and ToUint32(len)
is equal to len
, then the length property of the newly constructed object is set to ToUint32(len)
.
示例:
var a = Array(5);
a.forEach(function(element){
console.log('First log:', element)
});
a[2] = true;
a[3] = undefined;
a.forEach(function(element){
console.log('Second log:', element)
});
var b = [];
b[999] = 'Foobar';
b.forEach(function(element){
console.log('Third log:', element)
});
如您在控制台中所见,它只是跳过没有设置值的索引。
我在我的网站上工作时不小心发现了以下数组行为,我真的无法理解。
如果我在我的脚本中写这样的东西:
Array(4).forEach(function(elem) {console.log(elem);});
我return 没有日志条目,或任何与此相关的内容。
相反,如果我这样写:
[undefined,undefined,undefined,undefined].forEach(function(elem) {console.log(elem);});
我确实得到了 4 个日志条目。
我的问题是,这是为什么呢?为什么我不获取数组构造函数的日志条目,而是使用 []
获取它们? constructor specification nor the forEach
specification 都没有真正避开 undefined
或帮助我理解这一点。
forEach()
executes the provided callback once for each element present in the array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined.
您初始化数组的方式确实设置了它的长度,但没有将数组中的值设置为任何值,因此 forEach
不会迭代这些元素:
If the argument
len
is a Number andToUint32(len)
is equal tolen
, then the length property of the newly constructed object is set toToUint32(len)
.
示例:
var a = Array(5);
a.forEach(function(element){
console.log('First log:', element)
});
a[2] = true;
a[3] = undefined;
a.forEach(function(element){
console.log('Second log:', element)
});
var b = [];
b[999] = 'Foobar';
b.forEach(function(element){
console.log('Third log:', element)
});
如您在控制台中所见,它只是跳过没有设置值的索引。