【发布时间】:2017-04-01 05:01:41
【问题描述】:
这是完整的代码:
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和比较呢?
【问题讨论】:
-
那么问题出在哪里?你只是不明白什么?您希望我们使用 if/else 结构为您提供替代方案吗?...
-
@chazsolo 不,我只需要有人解释那部分,其余的并不那么重要......如果你想为我的新知识提供另一种选择,我很高兴。
-
您应该通过 Liam 提供的链接阅读 API。它只是一个比较器函数,检查每个比较的长度属性。
标签: javascript arrays string explain