初学者:这个函数只给我第一个最长的字符串。如何使它输出具有相同长度的所有最大字符串?
var words = ["one", "two", "tree", "four", "five", "six", "seven", "eight", "nine"];
function LongestWords(array){
var longWord = array[0];
for (i = 0; i < array.length; i++){
if(array[i].length > longWord.length){
longWord = array[i];
}
}
return longWord;
}
console.log(LongestWords(words));
答案 0 :(得分:2)
您必须使用push
在数组上添加新元素。
var words = ["one", "two", "tree", "four", "five", "six", "seven", "eight", "nine"];
function LongestWords(array){
var longWord = [];
var longWordLen = 0;
for (i = 0; i < array.length; i++){
if (array[i].length > longWordLen){
//If the current word is longer, reset the longWord and push the current word
longWord = [];
longWord.push( array[i] );
longWordLen = array[i].length;
} else if( array[i].length == longWordLen) {
//If the current word is the same length, just push the current word
longWord.push( array[i] );
}
}
return longWord;
}
console.log(LongestWords(words));
答案 1 :(得分:1)
步骤1:查找最长字符串的长度
步骤2:过滤长度与最长字符串相同的字符串。
let words = ["one", "two", "tree", "four", "five", "six", "seven", "eight", "nine"];
let longest = words.sort(function (a, b) { return b.length - a.length; })[0].length;
let allongString = words.filter(function(string){ return string.length === longest})
console.log(allongString)
答案 2 :(得分:0)
在这种情况下,您需要一个循环来获取最长的单词。此方法的迭代次数为 O(n)。
排序,就像在这个answer中一样,具有 O(nlogn)的复杂性,然后是 O(n)的sinlge迭代。
var words = ["one", "two", "tree", "four", "five", "six", "seven", "eight", "nine"],
result = words.reduce(function (r, w, i) {
if (!i || r[0].length < w.length) {
return [w];
}
if (r[0].length === w.length) {
r.push(w);
}
return r;
}, undefined);
console.log(result);