更新时间:2022-11-11 10:21:57
使用words.push(str.split(" "))
时,数组words
看起来像
[
["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
]
另一个问题是,当您在for
中检查longest[0].length
的第一次迭代时,它是undefined
.导致错误
Another problem is that when you check longest[0].length
for the first iteration in the for
, it is undefined
. Which results in the error
未捕获的类型错误:无法读取未定义的属性长度"
Uncaught TypeError: Cannot read property 'length' of undefined
要解决这个问题,您可以使用 longest
作为 string
而不是 array
.并在 for
中,将 length
大于当前 longest
字符串的字符串分配给它.
To solve this, you can use longest
as string
instead of array
. And in the for
, assign the string having the length
greater than the current longest
string to it.
在函数的最后,可以返回最长的
字符串.
At the end of the function, you can return the longest
string.
问题/建议:
str.split(' ')
直接赋值给words
变量longest
作为 string
变量而不是 array
和 initialize
它为空字符串,即 ''
,避免上述错误longest
的长度和words
数组中的字符串words
数组中字符串的长度大于longest
,则更新longest
.s+
将字符串拆分
空格str.split(' ')
to directly assignment to words
variablelongest
as string
variable instead of array
and initialize
it to empty string, i.e. ''
, to avoid the above errorlongest
with the string in the words
arraywords
array is greater than the longest
, update the longest
.s+
to split
the string by spacesfunction findLongestWord(str) {
var words = str.split(/s+/);
var longest = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) {
longest = words[i];
}
}
return longest;
}
var longestWord = findLongestWord('The quick brown fox jumped over the lazy dog');
document.write('Longest Word: "' + longestWord + '"');
document.write('<br />Longest Word Length: ' + longestWord.length);