猿问

为什么用for循环功能会得到未定义的结果?

为什么这段代码返回未定义,我找不到原因


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

我应该得到最小字数


慕勒3428872
浏览 245回答 3
3回答

守着一只汪

您的for循环condition并被increment反转:for (var i=0 ; i++ ; i<splitted.length){ ...相反,应为:for (var i = 0; i < splitted.length; i++) { ...您还必须修复循环代码,因为它会在您内部if语句的两个分支中返回,这意味着将仅运行一次迭代。如果要返回最小单词的长度,请执行以下操作:function findShort(s) {&nbsp; let splitted = s.split(' ');&nbsp; let result = splitted[0].length;&nbsp; for (let i = 0; i < splitted.length; i++) {&nbsp;&nbsp; &nbsp; const looped = splitted[i].length;&nbsp; &nbsp; if (looped < result) {&nbsp; &nbsp; &nbsp; result = looped;&nbsp; &nbsp; }&nbsp; }&nbsp; return result;};console.log(findShort("bitcoin take over the world maybe who knows perhaps"));或更短一些,使用Array.prototype.reduce():function findShortest(s) {&nbsp; 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'));

慕桂英546537

令condition和increment 是错误的,你for loop还有循环内的代码,仅当您return在所有条件下都具有时,它才会检查第一个元素。这是正确的function findShort(s) {&nbsp; let splitted = s.split(' ');&nbsp; let result = splitted[0].length;&nbsp; let looped&nbsp; for (var i = 0; i < splitted.length; i++) {&nbsp; &nbsp; looped = splitted[i].length;&nbsp; &nbsp; if (looped < result) { result = looped }&nbsp; }&nbsp; return result;};console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

至尊宝的传说

您的for循环实现是错误的,应该是:for&nbsp;(var&nbsp;i=0;&nbsp;i<splitted.length;&nbsp;i++)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答