我想向每个arrPlayers中添加arrHoles。内部的arrHoles可以是0-20个对象。
有什么简单的方法吗?
如果代码中有什么错误,我是javascript新手,我需要一些反馈:D
let players = document.querySelectorAll('#players div');
let holes = document.getElementById('holes');
let arrPlayers = [];
let arrHoles = [];
for (let a = 0; a < holes.length; a++) {
arrHoles.push({
win: false,
lose: false,
push: false,
points: "2"
});
}
console.log(arrHoles);
players.forEach(function(index, value) {
//Legger til alle spillere
arrPlayers.push({
/*I WANT this EACH PLAYER GET THIS FOR EACH HOLE*/
/*holes: [{
win: false,
lose: false,
push: false,
points: "2"
}],*/
name: players[value].childNodes[0].data,
id: players[value].getAttribute("data-id")
});
//arrPlayers[value];
//arrPlayers.push(arrHoles);
});
答案 0 :(得分:0)
创建一个返回所需数组的函数,然后为每个播放器调用它:
function getHoles() {
let holes = document.getElementById('holes');
let arrHoles = [];
for (let a = 0; a < holes.length; a++) {
arrHoles.push({
win: false,
lose: false,
push: false,
points: "2"
});
}
return arrHoles
}
然后在创建播放器时调用它:
...
arrPlayers.push({
holes: getHoles(),
name: players[value].childNodes[0].data,
id: players[value].getAttribute("data-id")
});
...