is there a way to automatically create subobjects in an assignment after construction, i.e.
var obj = {};
obj.a.b.c=13;
the above gives me a "obj.a is undefined" error
i wrote a function to do this, but wond开发者_StackOverflow中文版ered if there was an easier way
_setObjectProperty(obj,13,['a','b','c']);
function _setObjectProperty(obj,value,loc)
{
    if(loc.length>1) {
        obj[loc[0]] = obj[loc[0]] || {};
        _setObjectProperty(obj[loc[0]],value,loc.splice(1));
    }
    else if(loc.length===1) {
        obj[loc[0]]=value;
    }
}
No, there's no built in way to do this in JavaScript. The only way is to create your own function like you did. If you want the convenience of the dot operator/notation you can use the following function:
var set = function(path, value, root) {
  var segments = path.split('.'),
      cursor = root || window,
      segment,
      i;
  for (i = 0; i < segments.length - 1; ++i) {
     segment = segments[i];
     cursor = cursor[segment] = cursor[segment] || {};
  }
  return cursor[segments[i]] = value;
};
set("a.b.c", 2);
console.log(a.b.c) // => 2
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论