2017-07-03 76 views
-2

我需要從句子中找到最長的單詞。最長單詞

我試過這個代碼來找到最大的單詞。

但我需要偶數字。

任何人都可以幫我嗎?

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

什麼是* 「甚至」 *字? – charlietfl

+0

如果句子中沒有單詞,預期的結果是什麼? – Hopeless

+0

偶數字是指字符長度可被2整除的單詞,或位置2,4,6,8等字。在任何情況下,它都是一個if check循環。 – Amit

回答

2

在使用模運算符if語句

arrWords.forEach(function(wrd) { 
if (wordlength < wrd.length && wrd.length % 2 == 0) { 
    wordlength = wrd.length; 
    word = wrd; 
} 

});

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