从 onclick 函数为对象赋值
Assigning value to object from the onclick function
我正在尝试创建一个函数来处理升级的购买。针对特定升级将通过将对象作为参数传递给函数(向上)和升级值(数量)来完成。
这是我的玩家对象:
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 )
我正在尝试创建一个函数来处理升级的购买。针对特定升级将通过将对象作为参数传递给函数(向上)和升级值(数量)来完成。
这是我的玩家对象:
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 )