Dynamic object literal in javascript?

六眼飞鱼酱① 提交于 2019-11-27 16:22:26

问题


Is it possible to creat an object literal on the fly? Like this:

var arr = [ 'one', 'two', 'three' ]; 

var literal = {}; 

for(var i=0;i<arr.length;i++)
{
   // some literal push method here! 

  /*  literal = {
        one : "", 
        two : "",
        three : ""
    }  */ 
}

Thus I want the result to be like this:

 literal = {
        one : "", 
        two : "",
        three : ""
    } 

回答1:


for ( var i = 0, l = arr.length; i < l; ++i ) {
    literal[arr[i]] = "something";
}

I also took the liberty of optimising your loop :)




回答2:


Use this in your loop:

literal[arr[i]] = "";



回答3:


You can use for...of for the sake of simplicity:

for (const key of arr) {
   literal[key] = "";
}


来源:https://stackoverflow.com/questions/1998735/dynamic-object-literal-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!