Board logo

标题: [JavaScript] reduce快速查找数组中其中一项值出现在的次数 [打印本页]

作者: swiper    时间: 2017-8-14 11:49     标题: 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




欢迎光临 关注前端这点事 (http://www.xinran001.com/bbs/) Powered by Discuz! 7.0.0