任何人都可以向我解释这些片段(只是与上面的评论一致)吗?
function wordRate(word, str) {
let words = str.match(/\w+/g) || [];
// What does these comparison or whatever it is?
return words.filter(w => w == word).length / words.length;
}
Array.filter需要一个函数作为第一个参数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
这里做了什么呢?
答案 0 :(得分:1)
(w => w == word)
相当于
(function(w){return w == word})
答案 1 :(得分:1)
要真正理解这一点,你必须将其分解。
ECMAScript 2015(最新版本的Javascript,以前称为ECMAScript 6)引入了arrow functions,它们基本上是匿名函数的语法糖。
而不是像
那样定义一个繁琐而笨拙的表达function(x) { return x*x;}
箭头功能允许您编写
(x) => x*x
其中函数参数在括号中指定,返回的结果紧跟箭头。
在这个特定的例子中,
words.filter(w => w == word).length / words.length;
可以改写为
words.filter(function(w) {return (w == word);}).length / words.length;
这很容易解释:我们发现words
数组的哪一部分仅由一个目标word
组成。
答案 2 :(得分:0)
所以这是一个Ecmascript 6(javaScript 6)功能。看这里 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions