Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - JavaScript通过变量设置对象键[重复](JavaScript set object key by variable [duplicate])

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:(我正在用JavaScript构建一些对象并将这些对象推入数组,将要使用的键存储在变量中,然后像下面这样创建对象:)

var key = "happyCount"; myArray.push( { key : someValueArray } ); but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key.(但是,当我尝试检查每个对象的对象数组时,键是"key"而不是变量键的值。) Is there any way to set the value of the key from a variable?(有什么方法可以通过变量设置键的值吗?) Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/(小提琴以获得更好的解释: http : //jsfiddle.net/Fr6eY/3/)   ask by Hunter McMillen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make the object first, then use [] to set it.(您需要先创建对象,然后使用[]进行设置。)

var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.push(obj); UPDATE 2018:(更新2018:) If you're able to use ES6 and Babel, you can use this new feature:(如果您能够使用ES6和Babel,则可以使用此新功能:) { [yourKeyVariable]: someValueArray, }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...