[英]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循環condition
和increment
反:
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
中的代碼, condition
和increment
順序在您中是錯誤的,
僅當您在所有情況下都有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.