如何在javascript中检索数组中相同值的数量?

时间:2013-09-21 07:02:45

标签: javascript arrays

var array = ['box','box','line','time','box']

例如:框重复几次

1 个答案:

答案 0 :(得分:0)

你走了:

    var array = ['box','box','line','time','box'],
    map = {},
    key;

array.forEach(function(item) {
    if (map[item] === undefined) {
        map[item] = 1;
    } else {
        map[item]++;
    }
});

for (key in map) {
    console.log(" key:", key, " repeated:", map[key]);
}