我有一个数组:

[1, 2, 3, 5, 2, 8, 9, 2]

我想知道数组中有多少个2。

在JavaScript中,没有for循环的最优雅的方法是什么?


当前回答

不使用循环通常意味着将进程交给一些使用循环的方法。

这里有一个讨厌循环的编码器可以以一定的代价来满足他的厌恶:

var a=[1, 2, 3, 5, 2, 8, 9, 2];

alert(String(a).replace(/[^2]+/g,'').length);


/*  returned value: (Number)
3
*/

如果indexOf作为数组方法可用,还可以重复调用indexOf,并每次移动搜索指针。

这不会创建一个新的数组,并且循环比forEach或过滤器更快。

如果你有一百万个会员可以查看,那就会有所不同。

function countItems(arr, what){
    var count= 0, i;
    while((i= arr.indexOf(what, i))!= -1){
        ++count;
        ++i;
    }
    return count
}

countItems(a,2)

/*  returned value: (Number)
3
*/

其他回答

为什么需要map或filter呢? Reduce是为这类操作而“诞生”的:

[1、2、3、5、2、8、9、2]。减少((count,2)=>count+(item==val), 0);

就是这样!(如果item==val在每次迭代中,那么1将被添加到累加器计数中,因为true将解析为1)。

作为函数:

function countInArray(arr, val) {
   return arr.reduce((count,item)=>count+(item==val),0)
}

或者,继续扩展你的数组:

Array.prototype.count = function(val) {
   return this.reduce((count,item)=>count+(item==val),0)
}

Array.prototype.count =函数(v) { Var c = 0; 对于(设I = 0;I < this.length;我+ +){ If (this[i] === v){ c++; } } 返回c; } Var arr = [1,2,3,5,2,8,9,2]; console.log (arr.count (2));/ / 3

一些更普通和现代的东西(2022年):

import {pipe, count} from 'iter-ops';

const arr = [1, 2, 3, 5, 2, 8, 9, 2];

const n = pipe(arr, count(a => a === 2)).first; //=> 3

这样做的好处是:

它不需要创建一个新的数组,所以它是内存高效的 对于任何Iterable和AsyncIterable都是一样的

这是javascript中的一行代码。

使用地图。在数组中找到匹配的值(v === 2),返回一个由1和0组成的数组。 使用减少。将该数组的所有值相加,得到所找到的总数。

[1, 2, 3, 5, 2, 8, 9, 2]
  .map(function(v) {
    return v === 2 ? 1 : 0;
  })
  .reduce((a, b) => a + b, 0);

结果是3。

我用这个:

函数countElement(数组,元素){ 令tot = 0; For (var el of array) { If (el == element) { 合计+ +; } } 返回合计; } var arr =(“a”、“b”、“a”,“c”,“d”,“一个”,“e”,“f”,“a”); “a”console.log (countElement (arr));/ / 4