函数参数未正确添加到JSON对象

时间:2017-01-12 04:55:54

标签: javascript json object

在我正在创建的游戏中,我有一个函数,它接受一个项目的名称和数量,并将其添加到JSON“Player Invetory”。

代码如下:

function inventory(addOrRemove, item, amount) {
console.log(item);
    if (addOrRemove == 'add') {
        if (player.inventory.item== undefined) {
            player.inventory.item= amount;
        } else {
            player.inventory.item= player.inventory.item+ amount;
        }
    } 
console.log(player.inventory)
}

以这种方式调用函数时的输出如下:

inventory('add','coin',10)
// In the console log on line 2, "item" is defined as "coin"
// The player invetory object as called for in the console on line 10 has one value, "item: 10"

现在,问题是它不会根据函数参数添加到数组中。我希望玩家库存对象为“player.inventory.coin:10”而不是“player.inventory.item:10”。这同样适用于任何项目,因此库存动态可以添加任何类型的唯一项目。

我找了其他类似的问题,但是找不到任何和我一样有问题的人,虽然可能是因为我不完全确定这个问题本身叫什么,但我确实付出了努力而且难倒了

2 个答案:

答案 0 :(得分:2)

您需要将item变量传递给inventory对象,如下所示:

player.inventory[item] = amount;

这将使用'coin'变量中的字符串item,并将其设置为inventory对象中的键:

player.inventory['coin'] = amount;

答案 1 :(得分:1)

像这样:

if (player.inventory[item] == undefined) {
     player.inventory[item] = amount;
} else {
    player.inventory[item] = player.inventory[item] + amount;
    // or: player.inventory[item] += amount;
}