【问题标题】:Javascript : ask an explanationJavascript:求解释
【发布时间】: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


【解决方案1】:

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"));

【讨论】:

  • 您的替代方案不提供与问题的给定函数相同的输出。
  • @chazsolo 为什么?该函数应该返回最长的单词。这就是我的功能也在做的事情
  • 问题中的代码会从每个单词中去除非字母数字字符,而您的则不会。我要说的是输出不同。 OP 的示例最长单词是“coderbyte”,但您的返回“$$$longest#”。不是说你的答案是,但不一样。
猜你喜欢
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2011-09-25
  • 2016-12-03
  • 2012-06-07
  • 2019-08-12
  • 1970-01-01
相关资源
最近更新 更多