0

I have a var called testItem and want to add to the 'amount' inside it. I've set up a function so if you pass through the id and amount it should pick up on which variable you're referring to, except it doesn't work:

function addItem(id, count){
    id.amount = id.amount + count;
}

var testItem = {
    amount: 0,
};

addItem("testItem",100);

alert(testItem.amount);

How do I refer to testItem.amount by using the 'id' parameter? Thanks

  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) (Hint: For global variables, `window` is the object they are properties of.) – CBroe Aug 11 '17 at 14:20

1 Answers1

0

You passed testItem as string instead of variable name.

function addItem(id, count) {
  id.amount += count;
}

var testItem = {amount: 0};
addItem(testItem, 100);

alert(testItem.amount);
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176