Javascript 如何不使用array.forEach(=>;count+;+;)对array.push(未定义)进行计数?

Javascript 如何不使用array.forEach(=>;count+;+;)对array.push(未定义)进行计数?,javascript,arrays,Javascript,Arrays,我的目标是将实际的未定义的推送到一个数组中,类似于newarray()。现在,如果使用array.push(未定义)并使用array.forEach(element=>count++)对其进行计数则仍将其计为元素 function test() { let object = [5,,,5,"hoomba"] object.push(undefined) let maxRetries = 0; object.forEach(element => maxRe

我的目标是将实际的
未定义的
推送到一个数组中,类似于
newarray()
。现在,如果使用
array.push(未定义)
并使用
array.forEach(element=>count++)对其进行计数
则仍将其计为元素

function test() {
  let object = [5,,,5,"hoomba"]
  object.push(undefined)
  let maxRetries = 0;
  object.forEach(element => maxRetries++);

  console.log(object);
  console.log(maxRetries);
}

test();
预期结果:

console.log(object) // [5, undefined, undefined, 5, "hoomba", undefined]
console.log(maxRetries) // 3
实际结果:

console.log(object) // [5, undefined, undefined, 5, "hoomba", undefined]
console.log(maxRetries) // 4
您可以计算出
未定义的
值并计算
长度

功能测试(){
让对象=[5,,,5,“hoomba”]
object.push(未定义)
常量maxRetries=object.filter(v=>v!==未定义)。长度
log('object:',object);
log('maxRetries:',maxRetries);
}

test()
在计数前添加对
未定义的
(或falsy值)的检查

元素!==未定义的&&maxRetries++

功能测试(){
让对象=[5,,,5,“hoomba”]
object.push(未定义)
设maxRetries=0;
forEach(element=>element!==undefined&&maxRetries++);
//或者添加falsy值(null,未定义,0,,)
//forEach(element=>element&&maxRetries++);
console.log(对象);
console.log(maxRetries);
}

test()是什么阻止你这样做,
如果(元素!==未定义)maxRetries++