我的数组看起来像这样:
var arr = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
如何从数组创建对象? 数组值成为对象的键,计数重复值成为对象的值
我想获得以下对象
{
"a" : 3
"b" : 1
"c" : 2
"d" : 2
}
答案 0 :(得分:3)
这是你想要达到的目标吗? https://jsfiddle.net/yf184qob/
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var obj = {};
for(var a in arr){
var temp = arr[a];
if(typeof obj[temp] == "undefined"){
obj[temp] = 0;
}
obj[temp]++;
}
console.log(obj);
答案 1 :(得分:0)
var arr =['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var cv ={};
for(var i=0;i<arr.length;i++)
{
if (!(arr[i] in cv))
{
cv[arr[i]] =1
}else
{
cv[arr[i]]=cv[arr[i]]+1;
}
}