查找字符串中长度最大的所有单词 [英] Find all the words in a string which have the greatest length
本文介绍了查找字符串中长度最大的所有单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串中找到长度最大的所有单词.
I want to find all the words from the string which have the greatest length.
目前,结果只是长度最大的第一个:'jumped1'
,而我想要它们全部: ['jumped1','jumped2']
.
At the moment, the result is just the first with the greatest length: 'jumped1'
, whereas I want them all: ['jumped1', 'jumped2']
.
我该如何调整以下内容?
How can I adapt the following?
function test(str) {
var newStr = str.split(' ');
var nu = 0;
var word =null;
for(var i=0; i < newStr.length; i++){
if(newStr[i].length > nu){
nu = newStr[i].length; // length
word = newStr[i]; // word
}
}
return word;
}
console.log(test("The quick brown fox jumped1 over the lazy dog - jumped2"));
推荐答案
找到最长的单词时,与其分配给变量 word
,而不是将其推入最长的单词数组,而不是将其分配给变量.找到新的最长单词时,您必须处理空白数组.
Instead of assigning to a variable, word
, when you find longest word, push it to an array of longest words. You have to handle blanking the array though when a new longest word is found.
function test(str) {
var split_string = str.split(' ');
var longest_length = 0;
var words = [];
for(let string of split_string){
if(string.length > longest_length){
words = [string];
longest_length = string.length;
} else if (string.length == longest_length){
words.push(string);
}
}
return words;
}
console.log(test("The quick brown fox jumped1 over the lazy dog - jumped2"));
这篇关于查找字符串中长度最大的所有单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文