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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

為什么用for循環(huán)功能會(huì)得到未定義的結(jié)果?

為什么用for循環(huán)功能會(huì)得到未定義的結(jié)果?

慕勒3428872 2021-04-09 18:15:05
為什么這段代碼返回未定義,我找不到原因function findShort(s){  let splitted = s.split(' ');  let result = splitted[0].length ;  let looped  for (var i=0 ; i++ ; i<splitted.length){     looped = splitted[i].length;    if (looped < result) {return looped}else {return result }}};console.log(findShort("bitcoin take over the world maybe who knows perhaps"));我應(yīng)該得到最小字?jǐn)?shù)
查看完整描述

3 回答

?
守著一只汪

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊

您的for循環(huán)condition并被increment反轉(zhuǎn):


for (var i=0 ; i++ ; i<splitted.length){ ...

相反,應(yīng)為:


for (var i = 0; i < splitted.length; i++) { ...

您還必須修復(fù)循環(huán)代碼,因?yàn)樗鼤?huì)在您內(nèi)部if語(yǔ)句的兩個(gè)分支中返回,這意味著將僅運(yùn)行一次迭代。


如果要返回最小單詞的長(zhǎng)度,請(qǐng)執(zhí)行以下操作:


function findShort(s) {

  let splitted = s.split(' ');

  let result = splitted[0].length;

  for (let i = 0; i < splitted.length; i++) { 

    const looped = splitted[i].length;

    if (looped < result) {

      result = looped;

    }

  }

  return result;

};

console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

或更短一些,使用Array.prototype.reduce():


function findShortest(s) {

  return s.split(/\s+/).reduce((out, x) => x.length < out ? x.length : out, s.length);

};

console.log(findShortest('bitcoin take over the world maybe who knows perhaps'));


查看完整回答
反對(duì) 回復(fù) 2021-04-22
?
慕桂英546537

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊

令condition和increment 是錯(cuò)誤的,你for loop還有循環(huán)內(nèi)的代碼,


僅當(dāng)您return在所有條件下都具有時(shí),它才會(huì)檢查第一個(gè)元素。


這是正確的


function findShort(s) {

  let splitted = s.split(' ');

  let result = splitted[0].length;

  let looped

  for (var i = 0; i < splitted.length; i++) {

    looped = splitted[i].length;

    if (looped < result) { result = looped }

  }

  return result;

};


console.log(findShort("bitcoin take over the world maybe who knows perhaps"));


查看完整回答
反對(duì) 回復(fù) 2021-04-22
?
至尊寶的傳說(shuō)

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊

您的for循環(huán)實(shí)現(xiàn)是錯(cuò)誤的,應(yīng)該是:

for (var i=0; i<splitted.length; i++)


查看完整回答
反對(duì) 回復(fù) 2021-04-22
  • 3 回答
  • 0 關(guān)注
  • 278 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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