Find the longest word in a string?(查找字符串中最长的单词?)
问题描述
我正在尝试编写一个基本的 javascript 函数来查找字符串中最长的单词并记录它的长度.
I am trying to write a basic javascript function to find the longest word in a string and log it's length.
到目前为止我有:
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');
这对我来说很有意义,但它给了我一个错误.我尝试了 console.logging 每个步骤,但它在 for 循环周围失败了.
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.
推荐答案
使用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+
将字符串拆分
空格
- 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);
这篇关于查找字符串中最长的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找字符串中最长的单词?


基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01