0

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?

4

3 回答 3

2

JavaScript 没有 C 的指针或 C++ 的引用的概念,所以你必须以不同的方式来做。与其尝试将引用存储在数组中,不如尝试使数组成为数据的唯一持有者。
这可能看起来像这样:

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

然后playerBSold,您可以使用players[1].sold. 现在,您可以根据需要使用变量来代替它1

于 2013-04-20T05:39:39.787 回答
0

只需仔细查看您正在将值设置为数组的代码。您正在替换 arr[0][1] 项目值。以前它是 playerASold 即 0,现在是 200。所以您没有为 playerSold 分配值。像这样:

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

并使用这个:

arr[0].playerASold=200.
于 2013-04-20T05:54:52.170 回答
0

Javascript 原语(在本例中为 Number)是不可变的。即,您不能更改它们的值。对数字的操作会创建新的数字。然而,对象是可变的。

正如 icktoofay 所建议的,在这里重构为具有 price 和 sold 属性的可变 Player 对象可能是一个好主意。

于 2013-04-20T05:55:21.687 回答