不太理解这个for循环和变量声明位置对返回值的影响

function findLongestWord(str) {

  var arr = [];

  arr = str.split(" ");

  str = arr[0];

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

    if(arr[i].length > str.length) {

      str = arr[i];

    }

  }

  return str.length;

}


findLongestWord("The quick brown fox jumped over the lazy dog");  //6

function findLongestWord(str) {

  var arr = [];

  arr = str.split(" ");

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

    str = arr[0];

    if(arr[i].length > str.length) {

      str = arr[i];

    }

  }

  return str.length;

}


findLongestWord("The quick brown fox jumped over the lazy dog");  //3

为什么是3?


慕标5832272
浏览 396回答 1
1回答

富国沪深

function findLongestWord(str) {&nbsp; &nbsp; var arr = [];&nbsp; &nbsp; arr = str.split(' ');&nbsp; &nbsp; for (var i = 0,str = arr[0]; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (arr[i].length > str.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str = arr[i];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return str.length;}var result = findLongestWord('The quick brown fox jumped over the lazy dog');console.log(result);for的每次循环开始都会执行一遍str = arr[0];,结果自然不对啦~把这个赋值放到var i = 0的后边(都是初始化赋值嘛)就可以了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript