Dynamic property name concatenation

微笑、不失礼 提交于 2019-12-31 03:28:05

问题


I'm looking for an easy way to assign to a variable depending on the value of another variable.

device.slot2_clipList[clipNumber] = singleClipDetails;

what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the var slotNumber, and write to the corresponding variable.

i tried

device.slot + device.slotNumber + _clipList[clipNumber]

but (obviously?), this doesn't work.

How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.) Thanks


回答1:


This is what bracket notation is for

var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;



回答2:


device['slotNumber' + _clipList[clipNumber] ]

Explanation:

foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.



来源:https://stackoverflow.com/questions/28749164/dynamic-property-name-concatenation

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