为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

湖上湖 2022-12-22 08:58:19
我的目标是将 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
查看完整描述

2 回答

?
一只斗牛犬

TA贡献1784条经验 获得超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();


查看完整回答
反对 回复 2022-12-22
?
慕后森

TA贡献1802条经验 获得超5个赞

您可以过滤掉undefined值并计算length


function 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();


查看完整回答
反对 回复 2022-12-22
  • 2 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号