Thomas Gaskin
Thomas Gaskin

Reputation: 1

How do I refer to a variable stored in an array instead of its value?

I have a set of variables which represent prices and number of items sold in a 2d array. I have sorted it in order to find the lowest price.

I'd like to set the second variable (number sold) of the first item (player A) to a value (200) by referring to the array.

For example:

var playerASold;

var arr=[
    [playerAPrice,playerASold],
    [playerBPrice,playerBSold],
    [playerCPrice,playerCSold]];

arr[0][1]=200;

this doesn't work, probably because playerASold currently has a value of 0 and it is trying to set 0=0.

How do I refer to the variable and not the value of the variable?

Upvotes: 0

Views: 73

Answers (3)

huwiler
huwiler

Reputation: 954

Javascript primitives (in this case Number) are immutable. I.e., you can't change their values. Operations on Numbers create new numbers. Objects are however mutable.

As icktoofay suggested, refactoring as mutable Player objects with price and sold properties is probably a good idea here.

Upvotes: 0

Amrendra
Amrendra

Reputation: 2077

Just take a close look at your code you are setting value to array.you are replacing arr[0][1] item value.previously it was playerASold i.e 0 and now 200.So you are not assigning value to playerSold.do like this:

var arr=[[playerAPrice:0,playerASold:0],[playerBPrice:0,playerBSold:0],   [playerCPrice:0,playerCSold:0]];

and use this:

arr[0].playerASold=200.

Upvotes: 0

icktoofay
icktoofay

Reputation: 129011

JavaScript has no notion of C's pointers or C++'s references, so you'll have to do it in a different way. Rather than trying to store references in an array, try making the array the sole holder of the data.
That might look like this:

var players = [
    { price: 5, sold: 1 },
    { price: 3, sold: 6 },
    { price: 9, sold: 2 }
];

Then rather than, say, playerBSold, you can use players[1].sold. Now you can use a variable in place of that 1 if you wanted.

Upvotes: 2

Related Questions