gpt4 book ai didi

Javascript - 将函数参数传递给变量名

转载 作者:行者123 更新时间:2023-11-30 11:07:55 26 4
gpt4 key购买 nike

我正在尝试将函数参数传递给变量(如果可能的话)以减少代码重复性和嵌套的 if 语句/switch 语句。通过研究,我发现 getElementById 引用需要放在引号中才能显示为 id。主要问题是,我可以将参数传递给变量名吗?

<body>
<div class="contain">
<h3 id="red">0</h3>
<h3 id="green">0</h3>
<h3 id="blue">0</h3>
<button onClick="player_one.addResource(4,green)">Add Green</button>
<button onClick="player_one.addResource(3,red)">Add Red</button>
<button onClick="player_one.addResource(7,blue)">Add Blue</button>
</div>

<script>
var redResource = 0;
var greenResource = 0;
var blueResource = 0;

var player_one = {
addResource: function(num,color){
(color)Resource += num
document.getElementById(color).innerHTML =((color)Resource);
}

}

</script>
</body>
--------------------------------------------------------------------
--------------------------------------------------------------------
//with a different approach, I still have an issue
var player_one = {
addResource: function(num,color){
player_one.color += num
document.getElementById(color).innerHTML = (player_one.color);
},

red: 0,
green: 0,
blue: 0


}

最佳答案

您可以使用对象来代替变量:

var resources = {
red: 0,
green: 0,
blue: 0
};

var player_one = {
addResource: function(num, color) {
resources[color] += num;
document.getElementById(color).innerHTML = resources[color];
}
};

关于Javascript - 将函数参数传递给变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54930630/

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