Javascript动态数组和对象

Javascript动态数组和对象,javascript,arrays,loops,object,Javascript,Arrays,Loops,Object,这可能吗? 所以我需要一个具有动态名称和内容的数组,这些内容可以扩展和访问 object = {}; var two = ['thing', 'thing2']; for(one in two){ object[two[one]] = []; } 如果是,但不是以这种方式,那么如何做?这肯定是可行的,只需确保对象拥有该属性,并且它不是从原型链的更高层继承的: object = {}; var two = ['thing', 'thing2']; 中的 for(var one in t

这可能吗?

所以我需要一个具有动态名称和内容的数组,这些内容可以扩展和访问

object = {};
var two = ['thing', 'thing2'];
for(one in two){
    object[two[one]] = [];
}

如果是,但不是以这种方式,那么如何做?

这肯定是可行的,只需确保对象拥有该属性,并且它不是从原型链的更高层继承的:

object = {};
var two = ['thing', 'thing2'];
中的

for(var one in two){
    if(two.hasOwnProperty(one))
       object[two[one]] = [];
}
对于

for(var i = 0; i < two.length; i++)
   object[two[i]] = [];
for(变量i=0;i<2.length;i++)
对象[two[i]]=[];
var object={};
var props='thingthing2'。拆分(“”);

对于(var i=0,len=props.length;iEh?我不知道你在问什么。另外,使用
for in
迭代
数组被认为是不好的做法;使用C-style
for
循环或使用
Array.prototype.forEach
如果可用。对不起,很难为我解释:\n注意,你展示的代码示例声明了一个global
one
变量,除非函数中的其他地方有
var one
。迭代对象属性的最佳实践是
for(obj中的var prop){if(obj.hasOwnProperty(prop)){…}}
。在one上缺少
var
,导致它被全局定义(并可能发生冲突).@Phrogz,哎呀。错过了那个。谢谢!
var object = {};
var props  = 'thing thing2'.split(' ');
for (var i=0,len=props.length;i<len;++i){
  object[props[i]] = [];
}