在JavaScript中初始化“多维”对象 [英] Initializing a 'multidimensional' object in javascript
问题描述
在定义所有尺寸之前尝试在javascript中填充多维对象时遇到问题。
I'm having an issue with trying to populate a multidimensional object in javascript before all of the dimensions are defined.
例如,这就是我要执行的操作:
For example this is what I want to do:
var multiVar = {};
var levelone = 'one';
var leveltwo = 'two';
multiVar[levelone][leveltwo]['levelthree'] = 'test'
必须用这样的一行创建每个维度非常麻烦:
It would be extremely cumbersome to have to create each dimension with a line like this:
var multiVar = {};
multiVar['levelone'] = {};
multiVar['levelone']['leveltwo'] = {};
multiVar['levelone']['leveltwo']['levelthree'] = 'test'
之所以需要不使用迭代底漆就这样做是因为我不知道会有多少个维度,也不知道它会有什么键。它必须是动态的。
The reason why I need to do it without iterative priming is because I don't know how many dimensions there will be nor what the keys it will have. It needs to be dynamic.
有没有办法动态地做到这一点?
Is there a way to do that in a dynamic way?
推荐答案
您可以编写一个函数来确保存在必要的尺寸,但是您将无法使用点或括号符号来获得这种安全性。像这样的东西:
You could write a function which ensures the existence of the necessary "dimensions", but you won't be able to use dot or bracket notation to get this safety. Something like this:
function setPropertySafe(obj)
{
function isObject(o)
{
if (o === null) return false;
var type = typeof o;
return type === 'object' || type === 'function';
}
if (!isObject(obj)) return;
var prop;
for (var i=1; i < arguments.length-1; i++)
{
prop = arguments[i];
if (!isObject(obj[prop])) obj[prop] = {};
if (i < arguments.length-2) obj = obj[prop];
}
obj[prop] = arguments[i];
}
示例用法:
var multiVar = {};
setPropertySafe(multiVar, 'levelone', 'leveltwo', 'levelthree', 'test');
/*
multiVar = {
levelone: {
leveltwo: {
levelthree: "test"
}
}
}
*/
这篇关于在JavaScript中初始化“多维”对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!