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"); //6function 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?
1 回答
富国沪深
TA贡献1790条经验 获得超9个赞
function findLongestWord(str) {
var arr = [];
arr = str.split(' ');
for (var i = 0,str = arr[0]; i < arr.length; i++) {
if (arr[i].length > str.length) {
str = arr[i];
}
}
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
的后边(都是初始化赋值嘛)就可以了。
添加回答
举报
0/150
提交
取消