你不能得到
var data = [14:"A",5:"IMG",2:"SPAN"]
因为那不是有效的 JavaScript。此外,如果不同标签的计数最终相似,您将获得重复的键。转动键/值,并使用 JavaScript 对象:
var reduced = {A: 14, IMG: 6, SPAN: 2};
在 Ecmascript 5 中:
var data = ["A","A","A","IMG","IMG","A","A","IMG","A","A","IMG","A","A","IMG","IMG","A","A","A","A","A","SPAN","SPAN"];
var reduced = data.reduce(function (result, item) {
result[item] = (result.hasOwnProperty(item) ? result[item] : 0) + 1;
return result;
}, {});
console.log(reduced); // Object {A: 14, IMG: 6, SPAN: 2}
jsFiddle在这里
如果需要支持不带reduce的浏览器,可以在underscore.js中找到reduce
var reduced = _.reduce(data, function (result, item) {
result[item] = (result.hasOwnProperty(item) ? result[item] : 0) + 1;
return result;
}, {});
jsFiddle 带下划线