返回列表 回复 发帖

[JavaScript] reduce快速查找数组中其中一项值出现在的次数

  1. const originalArray = ["Alice", "Bob", "Charlie", "Bob", "Bob", "Charlie"];const numberOfBobs = originalArray.reduce(function(accumulator, item) {    if (item === "Bob") {        return accumulator + 1;    } else {        return accumulator;    }}, 0);console.log(numberOfBobs); // -> 3
复制代码
使用ES6的箭头函数:
  1. const numberOfBobs = originalArray.reduce((accumulator, item) => {    if (item === "Bob") {        return accumulator + 1;    } else {        return accumulator;    }}, 0);
复制代码
参考:
http://www.w3cplus.com/javascript/which-array-function-when.html

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
返回列表