[英]Javascript: multi-dimensional object
我想创建一个 object,从以下内容开始:
var map = {};
然后,我想用这个 function 添加项目:
add = function(integerA, objectB) {
map[objectB.type][integerA] = objectB;
}
所以,这是我想要实现的 object 结构的随机示例:
map = {
'SomeType' : { 0 : 'obj', 2 : 'obj', 3 : 'obj' },
'OtherType' : { 0 : 'obj', 5 : 'obj' },
};
现在,我的问题。 我不能做map[objectB.type][integerA] = objectB;
因为map[objectB.type]
没有定义。 我可以通过 if 语句检查map[objectB.type]
是否存在并创建map[objectB.type] = {};
来解决这个问题。 必要时。
否则我可以预加载所有 object 类型。 但是,我宁愿不必这样做。
我的问题:有没有一种方法可以“即时”创建 object 而不必在每次我想调用add
function 或预加载所有类型时检查类型是否已经存在?
It is important that my add function is so fast as possible and that the map object is correct, because I need to read and write a lot in a small amount of time (it's an animation / game application).
不,没有其他方法可以即时创建对象。 每次只检查是否存在:
add = function(integerA, objectB) {
if (!map[objectB.type]) {
map[objectB.type] = {};
}
map[objectB.type][integerA] = objectB;
}
如果你想提高性能,你可以考虑一些缓存技术。
您可以使用 boolean OR 快捷方式(至少避免显式if
)。 虽然它可能不那么可读:
var data = map[objectB.type] || (map[objectB.type] = {});
data[integerA] = objectB;
这是有效的,因为赋值实际上返回了被赋值的值,而 OR 表达式返回了第一个计算结果为true
的值。
我不认为使用if
对性能有任何影响(实际上,我的回答方式可能会“更慢”)。
如果您仅将 map 用于查找并且不需要迭代维度,则可以将维度合并为一个键。 例如:
add = function(integerA, objectB) {
var key = objectB.type + '-' + integerA;
map[key] = objectB;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.