最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic property name concatenation - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Feb 26, 2015 at 17:57 George Mauer 122k140 gold badges396 silver badges630 bronze badges asked Feb 26, 2015 at 17:41 Paul SchneiderPaul Schneider 3252 gold badges6 silver badges18 bronze badges 4
  • 1 Create and use a device.slots array instead? – Ry- Commented Feb 26, 2015 at 17:42
  • Although I gave the answer, I do agree with @minitech there is probably a better way for your code to be constructed. Having to do this, while perfectly possible is unusual and could lead to errors down the line. – George Mauer Commented Feb 26, 2015 at 17:54
  • Also I changed the title of your question. What you're doing is concatenating to get a property name. Doing that for a variable (which is not attached to an object) is much harder. – George Mauer Commented Feb 26, 2015 at 17:58
  • Does this answer your question? Dynamically access object property using variable – outis Commented May 12, 2022 at 20:16
Add a ment  | 

2 Answers 2

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论