gpt4 book ai didi

javascript - 从 onclick 函数为对象赋值

转载 作者:行者123 更新时间:2023-11-30 12:18:18 25 4
gpt4 key购买 nike

我正在尝试创建一个函数来处理升级的购买。针对特定升级将通过将对象作为参数传递给函数(向上)和升级值(数量)来完成。

这是我的播放器对象:

var player = {
tech: 0,
energy: 0,
upgrades:{
engi5Perc: 0,
engi25Perc: 0,
andro5Perc: 0,
andro25Perc: 0,
robot5Perc: 0,
robot25Perc: 0
}
}

这是我的功能:

function buyUpgrade(techcost, energycost, up, amount){
if(techcost <= player.tech && energycost <= player.energy){
player.tech -= techcost;
player.energy -= energycost;
up = amount;
console.log("Done, upgrade purchased");
}
}

我的 HTML:

<button type="button" onclick="buyUpgrade(1, 1, 'player.upgrades.engi5Perc', 0.005 )">Buy 5%</button>

我的函数中一定存在某种简单的错误,我花了很多时间试图找出它。到目前为止没有运气。

最佳答案

您当前正在将金额分配给字符串 'player.upgrades.engi5Perc'。这行不通。

但是您可以使用方括号来处理某些您只在运行时知道其名称的对象的属性,例如obj[propertyName] = value

这里有更多的例子来说明区别:

var obj = {foo: 'bar'};
var propertyName = 'foo';
// the following two assignments are essentially equal:
obj.foo = 'newBar';
obj[propertyName] = 'newBar';
// while this one is obviously assigning 'newBar' to the wrong property:
obj.propertyName = 'newBar';
// and this is what happens in your function:
'obj.foo' = 'newBar';

试试这个:

function buyUpgrade(techcost, energycost, up, amount){
if(techcost <= player.tech && energycost <= player.energy){
player.tech -= techcost;
player.energy -= energycost;
player.upgrades[up] = amount;
console.log("Done, upgrade purchased");
}
}

并仅使用升级的名称调用该函数:

buyUpgrade(1, 1, 'engi5Perc', 0.005 )

关于javascript - 从 onclick 函数为对象赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31785678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com