这里是完整的代码:
function LongestWord(sen) {
// we use the regex match function which searches the string for the
// pattern and returns an array of strings it finds
// in our case the pattern we define below returns words with
// only the characters a through z and 0 through 9, stripping away punctuation
// e.g. "hello$% ##all" becomes [hello, all]
var arr = sen.match(/[a-z0-9]+/gi);
// the array sort function takes a function as a parameter
// which is used to compare each element in the array to the
// next element in the array
var sorted = arr.sort(function(a, b) {
return b.length - a.length;
});
// this array now contains all the words in the original
// string but in order from longest to shortest length
// so we simply return the first element
return sorted[0];
}LongestWord("the $$$longest# word is coderbyte");
但我只需要有人解释这一部分:
var sorted = arr.sort(function(a, b) {
return b.length - a.length;
});
我确实理解功能和排序是如何工作的,但它有点混合,我的大脑崩溃了。
你也可以给我另一个简单的替代来解决这个问题>>最长的单词,我使用if-else
和比较的内容是什么?
答案 0 :(得分:0)
对于sort()
功能,您可以参考documentation
有关更简单的替代方法,请参阅以下代码
function LongestWord(sen) {
let longest = "";
sen.match(/[a-z0-9]+/gi).forEach(function(word) {
if (word.length > longest.length)
longest = word;
})
return longest;
}
console.log(LongestWord("the $$$longest# word is coderbyte"));