[英]Use array instead of object in JavaScript
I have the following var: 我有以下变量:
filter = {
"country": 1,
"Age Group": {},
"Gender": {},
"NEWSEC": {},
"Telco_Segment": {}
};
and function: 和功能:
function facetBuilder(key, val)
{
if(key == 'country')
{
filter.country = val;
}
else
{
if(typeof filter[key][val] !== "undefined" )
{
delete filter[key][val]; //I'm assuming you want to remove it
}
else
{
filter[key][val] = true;
}
}
console.log(filter);
}
The resulting object ends up looking something like this: 结果对象最终看起来像这样:
filter = {
"country": 1,
"Age Group": {
4: true,
3: true,
2: true
},
"Gender": {
1: true
},
"NEWSEC": {
3: true,
2: true
},
"Telco_Segment": {}
};
but what I really want is something like this: 但是我真正想要的是这样的:
filter = {
"country": 1,
"Age Group": [4,3,2],
"Gender": [1],
"NEWSEC": [3,2],
"Telco_Segment": []
};
And I'm not sure how to approach it. 我不确定该如何处理。
Instead of 代替
filter[key][val] = true;
how about 怎么样
filter[key].push(val);
and 和
filter = {
"country": 1,
"Age Group": [],
^^---empty array, instead of {} for object.
What you have now, if(typeof filter[key][val] !== "undefined" )
, is good, because objects have constant-time lookups. 现在您拥有的if(typeof filter[key][val] !== "undefined" )
很好,因为对象具有恒定时间的查找。 If you use an array scan, if(filter[key].indexOf(val) !== -1)
, the time complexity increases to O(n) because you'd have to scan each element to see if it's in the array. 如果使用数组扫描if(filter[key].indexOf(val) !== -1)
,则时间复杂度会增加到O(n),因为您必须扫描每个元素以查看其是否在数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.