如何自动将属性添加到未定义的对象? [英] How to automatically add properties to an object that is undefined?
问题描述
是否有一种简单的方法可以自动将属性添加到对象(如果属性尚不存在)?
Is there an easy way to automatically add properties to objects if they don't already exist?
请考虑以下示例:
var test = {}
test.hello.world = "Hello doesn't exist!"
这不起作用,因为未定义 hello
.
This doesn't work because hello
isn't defined.
之所以这样问,是因为我有一些不知道它们是否已经存在 hello
的现有对象.实际上,我在代码的不同部分中有很多这些对象.总是检查 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屋!