gpt4 book ai didi

javascript - 是否有类似于 Python Counter 函数的 Javascript 函数?

转载 作者:太空狗 更新时间:2023-10-29 22:15:52 25 4
gpt4 key购买 nike

我正在尝试将我的程序从 Python 更改为 Javascript,我想知道是否有一个 JS 函数,例如 Python 的集合模块中的 Counter 函数。

计数器语法

from collection import Counter
list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']
counter = Counter(list)
print counter

输出

Counter({'a':5, 'b':3, 'c':2})

最佳答案

DIY JavaScript 解决方案:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];

function Counter(array) {
var count = {};
array.forEach(val => count[val] = (count[val] || 0) + 1);
return count;
}

console.log(Counter(list));

JSFiddle example

更新:

使用构造函数 函数的替代方案:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];

function Counter(array) {
array.forEach(val => this[val] = (this[val] || 0) + 1);
}

console.log(new Counter(list));

JSFiddle example

关于javascript - 是否有类似于 Python Counter 函数的 Javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com