且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算数组中的元素并将其添加到对象中

更新时间:2023-12-02 23:10:10

count 的赋值用于由于后缀增量 计数++ 。这将为您提供计数器的值,并在以后增加。如果您使用前缀递增 ++ count ,则会获得分配的递增值。

The assignment of count, which is used in the loop, does not work in this case, because of the postfix increment count++. This gives you the value of the counter and increment later, If you take the prefix increment ++count, you get the incremented value assigned.


// Postfix 
var x = 3;
y = x++; // y = 3, x = 4

// Prefix
var a = 2;
b = ++a; // a = 3, b = 3


但是您可以省略变量并直接使用对象的属性进行计数。

But you can omit the variable and count directly with a property of the object. for all items in one loop.

您可以将元素用作对象的键。然后分配零(如果不存在则递增)。

You could use the element as key for the object. Then assign with zero, if not exist and increment.

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    for (var i = 0; i < input.length; i++) {
        obj[input[i]] = obj[input[i]] || 0;
        obj[input[i]]++;
    }
    return obj;
}

console.log(orgNums(arr));

上述内容的更紧凑版本,其中 Array#forEach

A more compact version of the above with Array#forEach

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    input.forEach(function (item) {
        obj[item] = (obj[item] || 0) + 1;
    });
    return obj;
}

console.log(orgNums(arr));