以防它被贴上重复或类似的标签;我只是想把它放在那里,我花了大约3-4天的时间寻找答案。出现的文章、主题和相关问题并没有解决我的问题。如果它们真的是解决方案,我现在不知道,也不明白为什么。
例如,如何遍历player对象的所有实例并返回id属性的每个实例的值?
function player(id, damage, arena)
{
this.id = id;
this.damage = damage;
this.arena = arena;
}
var player1 = new player(101,10, true);
var player2 = new player(102,5, true);
var player3 = new player(103,20, true);别嘲笑我!尽管我有65%的把握一个字符串不会作为一个对象的引用,但我所有的想法都倾向于回到像这样工作的东西上。
var txt = "";
for (i=1; i <= player_count; i++)
{
var x = "player"+i;
txt += " " + x.id;
}
document.GetElementById("someTextDivOrSomething").innerHTML = txt;有没有人能解释一下我该怎么做,或者给我指个正确的方向?
发布于 2015-10-15 07:47:37
你需要一些structure来保存data,也就是你创建玩家时的表示。
稍后,您可以循环遍历您的播放器集合的elements of
例如:
let players = {};
...
players[101] = new player(101,10, true);
players[102] = new player(102,15, true);
players[103] = new player(103,20, true);
...
let txt = ""
for (let p of players) {
txt += " " + p.id
// note we need a name which is not "player" as that is taken
}发布于 2015-10-18 01:41:09
您可以为对象构造函数使用闭包。私有变量players包含类Player的所有实例。
var Player = function () {
var players = [];
return function(id, damage, arena) {
this.id = id;
this.damage = damage;
this.arena = arena;
this.players = players;
this.players.push(this);
};
}();
var player1 = new Player(101, 10, true);
var player2 = new Player(102, 5, true);
var player3 = new Player(103, 20, true);
document.write(player1.players.length + '<br>'); // 3
document.write(player2.players.length + '<br>'); // 3
player3.players.forEach(function (a) { document.write('id: ' + a.id + '<br>'); }); // 101, 102, 103
https://stackoverflow.com/questions/33178306
复制相似问题