sid*_*ube 5 javascript ecmascript-6
因此,我在名为“tiles”的类中有一个属性,其中包含有关跳棋棋盘游戏状态的信息。每次我做出合法的移动以及游戏开始时,我都会尝试将此属性推送到名为“移动”的数组中。但问题是,每次我推送新的tiles属性时,moves数组中的先前元素都会更改为最新推送的tiles的值。
我知道发生这种情况是因为该对象是通过引用传递的,因此替换了数组中的旧元素,因为它们现在指向同一个对象,这是属性图块的最新值。因此,通过下面给出的代码,有没有一种方法可以不通过引用来推送该对象,而是通过合法移动导致的“图块”的每个不同的单独状态来推送该对象。
这是我的代码片段:App.js
App = function () {
var self = this;
self.tiles = [];
// this is populated with objects from a json file
//code to fetch json and save it to self.tiles
//more code
this.startGame = function () {
//other code
self.moves.push(self.tiles);
};
this.makeMove = function () {
//other code
self.moves.push(self.tiles);
};
};
Run Code Online (Sandbox Code Playgroud)
所以我期望的是在 self.moves 数组中,图块应该指向不同的对象而不是同一对象。它应该包含 self.tiles 的不同状态,但现在,当我推送属性时,“moves”数组的元素被最新的 self.tiles 值覆盖。
任何解决此问题的帮助都将受到高度赞赏。谢谢!
您应该用于JSON.parse(JSON.stringify())克隆嵌套对象。您可以用于Object.assign克隆浅对象
App = function () {
var self = this;
self.tiles = [];
// this is populated with objects from a json file
//code to fetch json and save it to self.tiles
//more code
this.startGame = function () {
//other code
self.moves.push(JSON.parse(JSON.stringify(self.tiles)));
};
this.makeMove = function () {
//other code
self.moves.push(JSON.parse(JSON.stringify(self.tiles)));
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6112 次 |
| 最近记录: |