在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');`
非常感谢
答案 0 :(得分:0)
您可以console.log
使用i
,words[i]
和maxLength
的输出来了解正在发生的事情。
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;