我有一个数组:

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

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

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


当前回答

我相信您可以使用JavaScript的新Set数组方法来拥有唯一的值。

例子:

var arr = [1, 2, 3, 5, 2, 8, 9, 2]
var set = new Set(arr);
 
console.log(set);

// 1,2,3,5,8,9。我们得到唯一的值作为输出。

其他回答

我是js数组的reduce函数的开始粉丝。

const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)

事实上,如果你真的想要花哨一点,你可以在Array原型上创建一个count函数。然后你就可以重复使用了。

Array.prototype.count = function(filterMethod) {
  return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
} 

然后做

const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)

为什么需要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)
}

下面是ES2017+获取O(N)中所有数组项计数的方法:

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

arr.forEach((el) => {
  counts[el] = counts[el] ? (counts[el] + 1) : 1;
});

你也可以选择对输出进行排序:

const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);

console.log(countsSorted)用于示例数组:

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

现代JavaScript:

请注意,在JavaScript (JS)中进行比较时,应该始终使用三重=== =。三重等号确保JS的比较在其他语言中表现得像双等号==(有一个例外,见下文)。下面的解决方案展示了如何用函数的方式解决这个问题,这将确保你永远不会出现越界错误:

// Let has local scope
let array = [1, 2, 3, 5, 2, 8, 9, 2]

// Functional filter with an Arrow function
// Filter all elements equal to 2 and return the length (count)
array.filter(x => x === 2).length  // -> 3

JavaScript中的匿名箭头函数(lambda函数):

(x) => {
   const k = 2
   return k * x
}

对于单个输入,可以简化为这种简洁的形式:

x => 2 * x

这里隐含了返回。

在JS中总是使用三重等号:=== =进行比较,除了检查可空性:if (something == null){},因为它包括检查未定义,如果你只使用双等号,就像在这种情况下。

如果您正在使用lodash或下划线_。countBy方法将提供一个由数组中的每个值键定的总计的对象。如果你只需要计算一个值,你可以把它变成一行代码:

_.countBy(['foo', 'foo', 'bar'])['foo']; // 2

这也适用于数字数组。示例中的一行代码是:

_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3