简体   繁体   中英

Dynamic property name concatenation

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

This is what bracket notation is for

var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM