如果未定义,则自动创建对象 [英] Automatically create object if undefined
问题描述
如果对象尚未存在,是否有一种简单的方法可以自动添加属性?
Is there an easy way to automatically add properties to objects if they don't allready exist?
请考虑以下示例:
var test = {}
test.hello.world = "Hello doesn't exist!"
这不起作用,因为 hello
isn我定义了。
This doesn't work because hello
isn't defined.
我之所以这样问是因为我有一些现有的对象我不知道它们是否已经有你好
与否。实际上我在代码的不同部分有很多这些对象。
总是检查 hello
是否存在以及它是否创建新对象非常烦人:
The reason why I'm asking this is because I have some existing objects for which I don't know if they allready have hello
or not. I actually have a lot of these objects in different parts of my code.
It is very annoying to always check if hello
exists and if it doesn't create a new object like:
var test = {}
if(test.hello === undefined) test.hello = {}
test.hello.world = "Hello World!"
有没有办法自动创建像 hello这样的对象
在这个例子中?
Is there a way to automatically create an object like hello
in this example?
我的意思是在php中类似的东西:
I mean something like that in php:
$test = array();
$test['hello']['world'] = "Hello world";
var_dump($test);
输出:
array(1) {
["hello"]=>
array(1) {
["world"]=>
string(11) "Hello world"
}
}
好吧,它是一个数组,但在js数组中,它与对象的问题相同。
Ok it's an array but in js arrays it is the same problem as with objects.
推荐答案
var test = {};
test.hello = test.hello || {};
test.hello.world = "Hello world!";
如果 test.hello
未定义,则为设置为空对象。
If test.hello
is undefined, it gets set to an empty object.
如果 test.hello
先前已定义,则保持不变。
If test.hello
was previously defined, it stays unchanged.
var test = {
hello : {
foobar : "Hello foobar"
}
};
test.hello = test.hello || {};
test.hello.world = "Hello World";
console.log(test.hello.foobar); // this is still defined;
console.log(test.hello.world); // as is this.
这篇关于如果未定义,则自动创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!