当元素未知时,如何获取数组中元素的数量

hml*_*lee 16 javascript arrays

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

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

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

{ 'Rhino': 2, 'Lion': 1, 'Dog': 1, 'Parrot': 2, 'Cat': 1, 'Zebra': 1 }
Run Code Online (Sandbox Code Playgroud)

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

var animalsCount = {};

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

animalsCount['Rhino'] = numberOfRhinos
Run Code Online (Sandbox Code Playgroud)

得到一个像我想要的对象.问题当然是根据动物的数量,这变得非常冗长和重复.同样,如果我不知道每种动物是什么,我就不能用这种方式创造物体.必须有一种方法可以在不知道这些信息的情况下做到这一点,但我被困住了.

Jua*_*des 19

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

    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
    */
Run Code Online (Sandbox Code Playgroud)

  • 当然,然后有人"拼错"`constrictor`作为"构造函数"或东西和事情变得奇怪. (5认同)

nic*_*ael 5

只需通过循环动物生成一本字典,然后将它再次循环通过你的动物.

    var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino'];
    var animals_dict={};
    for(var i=0;i<animals.length;i++){
        animals_dict[animals[i]]=0;
    }
    for(var i=0;i<animals.length;i++){
      animals_dict[animals[i]]=animals_dict[animals[i]]+1;
    }
    alert(JSON.stringify(animals_dict))
Run Code Online (Sandbox Code Playgroud)