第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

湖上湖 2022-12-22 08:58:19
我的目標(biāo)是將 actual 推undefined送到一個數(shù)組,類似于new Array(). 現(xiàn)在,如果你使用array.push(undefined)它并用array.forEach(element => count++)它來計數(shù),它仍然被算作元素。function test() {  let object = [5,,,5,"hoomba"]  object.push(undefined)  let maxRetries = 0;  object.forEach(element => maxRetries++);  console.log(object);  console.log(maxRetries);}test();預(yù)期結(jié)果:console.log(object) // [5, undefined, undefined, 5, "hoomba", undefined]console.log(maxRetries) // 3實際結(jié)果:console.log(object) // [5, undefined, undefined, 5, "hoomba", undefined]console.log(maxRetries) // 4
查看完整描述

2 回答

?
一只斗牛犬

TA貢獻(xiàn)1784條經(jīng)驗 獲得超2個贊

undefined在計數(shù)之前添加檢查(或虛假值)。


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


查看完整回答
反對 回復(fù) 2022-12-22
?
慕后森

TA貢獻(xiàn)1802條經(jīng)驗 獲得超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();


查看完整回答
反對 回復(fù) 2022-12-22
  • 2 回答
  • 0 關(guān)注
  • 77 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號