我需要从一个句子中找到最长的偶数词。
我已尝试使用此代码查找最大的单词。
但我需要平等的话。
有人可以帮助我吗?
function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '';
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length) {
wordlength = wrd.length;
word = wrd;
}
});
return word;
}
答案 0 :(得分:2)
在if语句中使用模运算符
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length && wrd.length % 2 == 0) {
wordlength = wrd.length;
word = wrd;
}
});
答案 1 :(得分:0)
function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '';
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length && !wrd.length%2) {
wordlength = wrd.length;
word = wrd;
}
});
return word;
}
答案 2 :(得分:0)
替代解决方案。
const longestWord = (str) => str.split(' ').filter(v => !(v.length % 2))
.sort((a,b) => b.length - a.length)[0];
console.log(longestWord('hi there hello four longer longestt'));
&#13;