最佳答案
如果对象不存在,是否有一种简单的方法可以自动将属性添加到对象中?
考虑下面的例子:
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 数组中,它的问题与对象相同。