gpt4 book ai didi

javascript - 在 javascript 中创建具有单独值的对象数组

转载 作者:行者123 更新时间:2023-11-28 20:21:48 25 4
gpt4 key购买 nike

我的 JavaScript 代码有问题。我使用一个循环执行该函数几次。

addGameButton = function(color,id) {
gameButton[gameButton.length] = new GameButton(color,id);
};

所以我有一个名为 gameButton 的 GameButton 对象数组。我正在尝试添加新的游戏按钮,每个按钮都有不同的颜色和 ID。然而,所有对象最终都具有相同的值。我认为我为数组赋值的方式有问题。下面是整个示例。

function GameButton(c, i) {
color = c;
id = i;
markup = '<div class="'+i+'"></div>';

this.getColor = function () {
return color;
};
this.getMarkup = function () {
return markup;
};
}

function GameBoard() {
gameButton = new Array();

addGameButton = function(color,id) {
gameButton[gameButton.length] = new GameButton(color,id);
};

this.createGameBoard = function (color) {

color = ["red", "green", "blue"];
addButtons(color);
};

addButtons = function (color) {
var i = 0;
for (i=0; i <color.length; i++) {
addGameButton(color[i],i);
}
};

this.getGameButton = function (index) {
return gameButton[index];
};
}

$(document).ready(function(){
gameBoard = new GameBoard();
gameBoard.createGameBoard();

b = gameBoard.getGameButton(0);
console.log(b.getColor());
// returns blue instead of red, also getGameButton(1) has the same values
});

最佳答案

问题是您在许多地方为全局窗口对象分配值,并且它们相互覆盖,从而导致困惑。您需要在本地创建变量来解决此问题。查看修订后的代码,其中包含解释更改内容的注释。

function GameButton(c, i) {
var color = c; //use var to avoid assigning this variable to window object
var id = i; //use var to avoid assigning this variable to window object
var markup = '<div class="'+i+'"></div>'; //use var to avoid assigning this variable to window object

this.getColor = function () {
return color;
};
this.getMarkup = function () {
return markup;
};
}

function GameBoard() {
//use var to avoid assigning this variable to window object
var gameButton = new Array();

//This will declare a local function intead of assigning the function to window object like in your code.
function addGameButton(color,id) {
gameButton[gameButton.length] = new GameButton(color,id);
};

this.createGameBoard = function (color) {

var col = color || ["red", "green", "blue"]; //Use default ["red", "green", "blue"] if there is no color passing in
addButtons(col);
};

//This will declare a local function intead of assigning the function to window object like in your code.
function addButtons(color) {
var i = 0;
for (i=0; i <color.length; i++) {
addGameButton(color[i],i);
}
};

this.getGameButton = function (index) {
return gameButton[index];
};
}

$(document).ready(function(){
//Declare a local variable.
var gameBoard = new GameBoard();
gameBoard.createGameBoard();

var b = gameBoard.getGameButton(0);
console.log(b.getColor());

});

关于javascript - 在 javascript 中创建具有单独值的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171395/

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