簡體   English   中英

為什么用for循環功能會得到未定義的結果?

[英]why I am getting undefined result with for loop function?

為什么這段代碼返回未定義,我找不到原因

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

我應該得到最小字數

您的for循環conditionincrement反:

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

相反,應為:

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

您還必須修復循環代碼,因為它會在內部if語句的兩個分支中返回,這意味着將僅運行一次迭代。

如果要返回最小單詞的長度,請執行以下操作:

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

您的for循環實現是錯誤的,應該是:

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

for loop以及for loop中的代碼, conditionincrement順序在您中是錯誤的,

僅當您在所有情況下都有return ,它才會檢查第一個元素。

這是正確的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM