如果尚不存在将属性自动添加到对象的方法,有没有简单的方法?
考虑以下示例:
var test = {}
test.hello.world = "Hello doesn't exist!"
这是行不通的,因为hello未定义。
我之所以这样问,是因为我有一些不知道它们是否已经存在的现有对象hello。实际上,我在代码的不同部分中有很多这些对象。总是检查是否hello存在以及是否不创建新对象(例如:
var test = {}
if(test.hello === undefined) test.hello = {}
test.hello.world = "Hello World!"
有没有一种自动创建对象的方法,如hello本例所示?
我的意思是在php中:
$test = array();
$test['hello']['world'] = "Hello world";
var_dump($test);
输出:
array(1) {
["hello"]=>
array(1) {
["world"]=>
string(11) "Hello world"
}
}
好的,这是一个数组,但是在js数组中,它与对象的问题相同。