Javascript 为什么forEach函数没有';不执行任何循环步骤
我在使用Array.prototype.forEach函数时遇到问题 这是我的代码,我想知道为什么forEach函数在没有初始值的情况下由数组构造函数创建数组时不执行任何循环步骤Javascript 为什么forEach函数没有';不执行任何循环步骤,javascript,arrays,Javascript,Arrays,我在使用Array.prototype.forEach函数时遇到问题 这是我的代码,我想知道为什么forEach函数在没有初始值的情况下由数组构造函数创建数组时不执行任何循环步骤 var arr = new Array(3) //arr : [undefined, undefined, undefined] arr.forEach(function(){ console.log('my code'); })//doesn't output the expected result //t
var arr = new Array(3) //arr : [undefined, undefined, undefined]
arr.forEach(function(){
console.log('my code');
})//doesn't output the expected result
//this works well
for(var i = 0, length = arr.length; i < length; i++)
console.log('output the expected result')
//this case works well too.
var arr2 = new Array(undefined, undefined, undefined) // arr2: [undefined, undefined, undefined]
arr2.forEach(function(){
console.log('my code');
})//works well
var arr=new Array(3)//arr:[未定义,未定义,未定义]
arr.forEach(函数(){
log(“我的代码”);
})//不输出预期结果
//这很有效
对于(变量i=0,长度=arr.length;i
来自(请注意粗体部分):
forEach()为存在的每个元素执行一次提供的回调
在数组中按升序排列不为索引调用它
已删除或未初始化的属性(即稀疏
数组)
因此,您的应用程序的行为是正确的。非常感谢,我之前忽略了这一重要行。如果您认为这是正确的答案,可以使用绿色标志进行检查。非常感谢。