找到一个字符串中最长的单词? [英] Find the longest word in a string?
问题描述
到目前为止,我有:
函数findLongestWord(str){
var words = [];
var longest = [];
words.push(str.split());
for(var i = 0; i if(words [i] .length> longest [0] .length){
longest.push (字[I]);
}
}
return longest [0] .length;
findLongestWord('快速的棕色狐狸跳过懒狗');
这对我来说非常合理,但是却给我一个错误。我尝试了console.logging的每一步,并绕着for循环失败。
当您使用 .push(str.split())
,数组 words
看起来像
[
[,quick,brown,fox,jumped,over,the,lazy狗]
]
另一个问题是当您检查最长的[0] .length
用于中的第一次迭代
,它是 undefined
。这导致错误
$ b
未捕获TypeError:无法读取未定义的属性'length'
为了解决这个问题,你可以使用 在函数结尾处,可以返回 问题/建议: 最长的
作为 string
,而不是阵列
。在中为
分配长度长度
大于当前长度最长的字符串
最长的
字符串
$ b
str.split('')
直接赋值给字
变量
最长的
作为字符串
变量而不是数组<$ code>和
initialize
它为空字符串,即''
,以避免上述错误
最长的
的长度与字
数组中的字符串进行比较
words
数组中的字符串长度大于 longest
,则更新最长。
\ s +
至分割
空格字符串
function findLongestWord (str){var words = str.split(/ \s + /); var longest =''; for(var i = 0; i
I am trying to write a basic javascript function to find the longest word in a string and log it's length.
So far I have:
function findLongestWord(str) {
var words = [];
var longest = [];
words.push(str.split(" "));
for(var i = 0; i < words.length; i++){
if (words[i].length > longest[0].length){
longest.push(words[i]);
}
}
return longest[0].length;
}
findLongestWord('The quick brown fox jumped over the lazy dog');
It makes perfect sense to me, yet it gives me an error. I tried console.logging each step and it fails around the for loop.
When you use words.push(str.split(" "))
, the array words
looks like
[
["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
]
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
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.
Problems/Suggestions:
- Use
str.split(' ')
to directly assignment towords
variable - Use
longest
asstring
variable instead ofarray
andinitialize
it to empty string, i.e.''
, to avoid the above error - Compare the length of the
longest
with the string in thewords
array - If the length of the string in
words
array is greater than thelongest
, update thelongest
. - Use
\s+
tosplit
the string by spaces
function 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);
这篇关于找到一个字符串中最长的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!