js,对象属性,数组

zpjshiwo77 2016-01-25 01:55:35
我可能对js理解不深的原因吧,不知道错在哪~

var housegame = function (num) {
this.players = {players:[]};//记录有多少位玩家玩家
this.player = {//玩家属性
name:"default",
money:"10",
landCount:0,
land:[],
landKey:0,
color:"#fff",
}
this.color = ["rgb(235, 110, 98)","rgb(249, 163, 108)","rgb(245, 173, 85)","rgb(50, 184, 176)","rgb(130, 148, 160)","rgb(129, 210, 238)","rgb(193, 153, 209)"];
this.init = function (options, onClose) {// 初始化游戏
//记录玩家数量 start
for(var i = 0;i < num;i++){
this.player.name = "player"+(i+1);
this.player.color = this.color[i+1];
this.players.players.push(this.player);
}
//记录玩家数量 end
};
// 更换主题
this.Ctheme =function(theme){
}
}

我新建了三个玩家,为什么得到的是:

为什么不是player1,player2,player3啊?
...全文
186 2 打赏 收藏 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zpjshiwo77 2016-01-25
  • 打赏
  • 举报
回复
引用 1 楼 showbo 的回复:
非常感谢,一看见你的代码我就恍然大悟了,我之前写的往数组中加入的是该对象的地址,而不是新对象。 哎~怪我读书少~
  • 打赏
  • 举报
回复
player变量是对象,你这样修改的都是player这个变量,而不是新建对象
           this.init = function (options, onClose) {// 初始化游戏
                //记录玩家数量 start
                for (var i = 0; i < num; i++) {
                    this.player = {};//////////////////新对象
                    this.player.name = "player" + (i + 1);
                    this.player.color = this.color[i + 1];
                    this.players.players.push(this.player);
                }
                //记录玩家数量 end
                console.log(this.players)
            };

87,984

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧