最长的偶数字

时间:2017-07-03 16:50:57

标签: javascript

我需要从一个句子中找到最长的偶数词。

我已尝试使用此代码查找最大的单词。

但我需要平等的话。

有人可以帮助我吗?

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;
}

3 个答案:

答案 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)

替代解决方案。

&#13;
&#13;
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;
&#13;
&#13;