gpt4 book ai didi

javascript - .forEach 方法将更新应用于数组中的所有项目而不是单个项目

转载 作者:行者123 更新时间:2023-11-30 12:02:48 25 4
gpt4 key购买 nike

我正在为我的一些学生做一个小练习,我正在自动化一种 10 瓶保龄球游戏,我已将其放入 JsBin 此处 https://jsbin.com/qilizo/edit?html,js,output .不知道是累了还是傻了,还是国定假日上类,有件事让我很不解。当我开始游戏时,我会提示用户设置一些所需的玩家。这会自动生成一个 Player 对象数组,如下所示:

[{score: Array[10], spareCount: 0, strikeCount: 0, username: "Player 1"}, ...]

现在,稍后我允许用户播放我们数组中的每个玩家都有两次 throw 的帧...我收集分数并将其添加到特定玩家的分数数组中。但是,当我尝试使用 .forEach 方法执行此操作时,我生成的分数将应用于我的 Players 数组中的所有项目(玩游戏并查看)。我已将我的代码放在 jsBin 中,问题出在第 109 行:a.score[currentFrame - 1] = playFrame();

我试图修改我的代码,但我无法弄清楚为什么当前(或最后)帧得分被应用到所有 Player 对象!如果您能理解我的语法错误并解释原因,我将不胜感激。玩游戏(设置好玩家号码后点击按钮)你就会明白我的意思了……

片段:

var players,
currentFrame = 0,
currentThrow = 0;

// helper functions
// Accurate isNumber function... Thank you Crockford (see JavaScript: The Good Parts)
function isNumber(value) {
return typeof(value === 'number') && isFinite(value);
}

function frameStyle(k) {

var returnCssClass,
k = k + 1;

if (k < currentFrame) {
returnCssClass = 'played-frame';
} else if (k === currentFrame) {
returnCssClass = 'current-frame';
} else {
returnCssClass = null;
}

return returnCssClass;

}

function setUpPlayers(num) {

var tempArray = [],
tempName = 'Player ',
emptyScores = Array(10).fill([-1, -1]); // set default to -1 as a rubbish player may hit no pins!

for (var i = 0; i < num; i++) {
tempArray.push({
username: tempName + (i + 1),
score: emptyScores,
strikeCount: 0,
spareCount: 0
}); // the way I have named the tempName is technically an antipattern!
}

return tempArray;
}

function getTotals(scores) {

var totalScore = scores.reduce(function(a, b) {
return a + b.reduce(function(c, d) {
return (c + (c + ((d > 0) ? d : 0)));
}, 0);
}, 0);

return totalScore;
}

function displayScore(score) {

// toDo reformat!
var formatScore = score.map(function(a, b) {
if (a === -1) {
a = '-';
} else if (a === 10) {
a = 'X';
}
return a;
});

return formatScore;
}

function createGrid() {

// If only I was using ES6 I could have multi line support!
var playerLen = players.length,
scoresLen = players[0].score.length;
boards = '<div class="score-board">' +
'<!-- one row for each player -->';
// need to loop this through the players...
for (var i = 0; i < playerLen; i++) {
boards += '<div class="row">' +
'<!-- first cell is the name -->' +
'<div class="name">' + players[i].username + '</div>';
// need to loop this with the users scores
for (var k = 0; k < scoresLen; k++) {
boards += '<div class="game ' + frameStyle(k) + ' ">' + displayScore(players[i].score[k]) + '</div>';
}
// don't forget the total
boards += '<div class="player-total">' + getTotals(players[i].score) + '</div>';
boards += '</div>';

}
boards += '</div>';
boards += '<div>Current Frame: ' + currentFrame + '</div>';
boards += '<button type="button" onclick="startGame()">Start Game</button>';
// fill the holder....
document.getElementById('boardHolder').innerHTML = boards;
}

function startGame() {

if (currentFrame >= 10) {
announceWinner();
} else {
currentFrame++;

// do the throws for Each Player!
players.forEach(function(a, b) {
a.score[currentFrame - 1] = playFrame();
});

// update the grid
createGrid();
// recurrrrrrsion....
//startGame();

}
}

function throwBall(pinsStanding) {
// i know it isn't a ball
return Math.floor(Math.random() * (pinsStanding + 1));
}

function playFrame() {
// here we just create the array and determine if we have a strike or a spare!
var pinsStanding = 10,
frameScore = [],
frameThrows = 2,
pinsDown;

for(var i = 0; i < frameThrows; i++) {

pinsDown = throwBall(pinsStanding);
pinsStanding = pinsStanding - pinsDown;

// if it is the pinsStanding = 0 and it is the first throw - a strike!
if(pinsStanding === 0 && i === 1) {
pinsStanding = 10;
frameThrows = 3;
}

// what if it is a spare?
frameScore.push(pinsDown);
}

return frameScore;
}

function announceWinner() {

}

// kick it all off!!!
window.onload = function() {
// lets get some users....
players = prompt('Please enter the NUMBER of players?', 2);

// check we have a number...
if (isNumber(players)) {
players = setUpPlayers(players);
createGrid();
}
};
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

/* classes */
.score-board {
border: 1px solid #000;
}

.row {
display: block;
border-bottom: 1px solid #000;
}

.row:last-child {
border-bottom: none;
}

.row > div {
display: inline-block;
padding: 5px;
}

.game {
border-right: 1px solid #000;
}

.name {
background-color: #f5f5f5;
border-right: 1px solid #000;
}

.player-total {
text-align: right;
background-color: #d5eabb;
}

.played-frame {
background-color: #aee1e8;
}

.current-frame {
background-color: #ffc0cb;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>

<h1>Let's go bowling!</h1>

<div id="boardHolder">
</div>

</body>
</html>

这是垃圾桶! https://jsbin.com/qilizo/edit?html,js,output

最佳答案

您需要在 for 循环中调用 Array(10).fill([-1, -1]),否则所有对象将共享相同的分数数组:

function setUpPlayers(num) {

var tempArray = [],
tempName = 'Player ';

for (var i = 0; i < num; i++) {
tempArray.push({
username: tempName + (i + 1),
score: Array(10).fill([-1, -1]),// set default to -1 as a rubbish player may hit no pins!
strikeCount: 0,
spareCount: 0
}); // the way I have named the tempName is technically an antipattern!
}

return tempArray;
}

https://jsbin.com/yeyupiteyu/1/edit?html,js,output

关于javascript - .forEach 方法将更新应用于数组中的所有项目而不是单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36222339/

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