如何不使用 array.forEach(_ => count++) 计算 array.push?

我的目标是将 actual 推undefined送到一个数组,类似于new Array(). 现在,如果你使用array.push(undefined)它并用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


湖上湖
浏览 93回答 2
2回答

一只斗牛犬

undefined在计数之前添加检查(或虚假值)。element !== undefined && maxRetries++function test() {  let object = [5,,,5,"hoomba"]  object.push(undefined)  let maxRetries = 0;  object.forEach(element => element !== undefined && maxRetries++);    // Alternatively add falsy value (null, undefined, 0, '')  // object.forEach(element => element && maxRetries++);  console.log(object);  console.log(maxRetries);}test();

慕后森

您可以过滤掉undefined值并计算lengthfunction test() {  let object = [5,,,5,"hoomba"]  object.push(undefined)    const maxRetries = object.filter(v => v !== undefined).length  console.log('object:', object);  console.log('maxRetries:', maxRetries);}test();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript