for循环嵌套如果控制流,JavaScript?

时间:2018-02-03 21:45:58

标签: javascript

在JavaScript代码中是否有任何方法,看看循环(特别是for循环)控制流是如何工作的,让我们说代码来识别给定数组中最长的字符串?如果有条件循环。

`

var maxLength = 0;
function findLongestWord(str) {
  var words = str.split(' ');
  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
}
  }
  return maxLength;
}
findLongestWord('The quick brown fox jumped over the lazy dog');`

非常感谢

1 个答案:

答案 0 :(得分:0)

您可以console.log使用iwords[i]maxLength的输出来了解正在发生的事情。

&#13;
&#13;
function findLongestWord(str) {
    var maxLength = 0,
        words = str.split(' '),
        i;

    for (i = 0; i < words.length; i++) {
        if (words[i].length > maxLength) {
            maxLength = words[i].length;
            console.log('change length to', maxLength);
        }
        console.log(i, words[i], maxLength);
    }
    return maxLength;
}

console.log(findLongestWord('The quick brown fox jumped over the lazy dog'));
&#13;
&#13;
&#13;