gpt4 book ai didi

javascript - 当元素未知时如何获取数组中元素的计数

转载 作者:可可西里 更新时间:2023-11-01 01:21:41 24 4
gpt4 key购买 nike

所以我想弄清楚如何生成一个关联数组,该数组列出数组的元素以及每个元素出现的次数,而事先不知道元素是什么。

举个例子,假设我有一组动物:var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra' , '犀牛']

我想生成一个最终看起来像这样的对象:

{ 'Rhino': 2, 'Lion': 1, 'Dog': 1, 'Parrot': 2, 'Cat': 1, 'Zebra': 1 }

如果我事先知道数组中的动物是什么,我当然可以这样做:

var animalsCount = {};

var numberOfRhinos = animals.filter(function(animal) {
return animal == 'Rhino'
}).length;

animalsCount['Rhino'] = numberOfRhinos

得到一个我想要的对象。当然,问题是根据动物的数量,这会变得相当冗长和重复。同样,如果我不知道每种动物是什么,我就无法以这种方式创建对象。必须有一种方法可以在不知道该信息的情况下执行此操作,但我被卡住了。

最佳答案

最简单的方法是创建一个 map ,将数组中的值初始化(为 1)作为该 map 上的一个属性。每次看到未定义的属性时,您都可以增加属性的值。

    function countObjs(arr) {
// So the object doesn't inherit from Object.prototype and avoids property
// name collisions
var obj = Object.create(null);
arr.forEach(function(item) {
if (obj[item]) {
obj[item]++;
} else {
obj[item] = 1;
}
});
return obj;
}
var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino'];
console.log(countObjs(animals));
/*
Cat: 1
Dog: 1
Lion: 1
Parrot: 2
Rhino: 2
Zebra: 1
*/

关于javascript - 当元素未知时如何获取数组中元素的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33657432/

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