# 将循环函数的值存储到变量javascript中

Luz4周前 (07-20)articles130

#### storing value of a looped function into a variable , javascript

• jose perez 问题:
• 嘿，我需要你的帮助。在这个石头剪纸游戏中，获胜者是第一个在用户和计算机之间赢得五场胜利的人。虽然我还没有循环这个，但我需要帮助将每次获胜的计数存储到变量中，从我的points（）函数到var playerPoints=0；orvar补偿点=0；取决于谁赢了这一轮。如果你有循环的建议，请随时建议我，以及！谢谢
• `    //decalring an array with weapons of choice    const weaponArray = ["rock", "paper", "scissors"];    // selects a random index from array to represent computer choice    const computerChoice = weaponArray[[Math.floor(Math.random() * weaponArray.length)]];    //prompts user to make a choice of weapon    const playerPrompt = prompt("Please enter Rock, Paper, or Scissors!");    //lowers all alphabet input to lower case    const playerChoice = playerPrompt.toLowerCase();             //function runs player vs computer choices and determines winner of round    const round = (computerChoice, playerChoice) => {      if (playerChoice === "scissors" && computerChoice === "rock" || playerChoice === "rock" && computerChoice === "paper" || playerChoice ==="paper" && computerChoice === "scissors") {      return "Just Give Up Now Looser!";    }      else if (playerChoice === "rock" && computerChoice === "scissors" || playerChoice === "paper" && computerChoice === "rock" || playerChoice==="scissors" && computerChoice === "paper")      {      return "You Won This Round!";    }    else {      return "Its a Tie!";    }    };        //stores round function value  into a variable     var state = round(computerChoice, playerChoice);         // adds points to player or computer based on "state" value   const points = () => {    if (state === "You Won This Round!"){      return playerPoints + 1;    }    else if (state === "Just Give Up Now Looser!"){      return compPoints + 1;    }    else{      return null    }      };          var playerPoints = points()  ;    var compPoints = points()  ;          console.log(state); console.log(points()); //console.log(compPoints); //console.log(playerPoints);`
• 回答:
• jose perez - vote: 1
• 不妨在这里加上我的答案。我不会使用即时方法，而是使用按钮。将分数存储在对象中，并使用条件检查是否有人在每场比赛后达到五分：
• `const userScore = document.querySelector('.user .score')const computerScore = document.querySelector('.computer .score')const resultContainer = document.querySelector('.result')const userThrowContainer = document.querySelector('.userThrow')const opponentThrowContainer = document.querySelector('.opponentThrow')const buttons = document.querySelectorAll('button')const score = {  user: 0,  computer: 0}function rpsMatch(userThrow) {  // Define possible throws  const throwOptions = [    'rock',    'paper',    'scissors'  ]    // Choose randomly from array of throws  let opponentThrow = throwOptions[Math.floor(Math.random() * throwOptions.length)]    // Print user and computer throws  userThrowContainer.innerText = `You threw \${userThrow}`  opponentThrowContainer.innerText = `Computer threw \${opponentThrow}`    function userWins() {    resultContainer.innerText = 'You win'    score.user++    updateScores()  }    function computerWins() {    resultContainer.innerText = 'You lose'    score.computer++    updateScores()  }    function updateScores() {    userScore.innerText = score.user    computerScore.innerText = score.computer  }    function resetScore() {    userScore.innerText = 0    computerScore.innerText = 0    score.user = 0    score.computer = 0  }    // RPS logic  if (userThrow == opponentThrow) {    resultContainer.innerText = 'You tied'  } else {    if (userThrow == 'rock') {      opponentThrow == 'scissors' ? userWins() : computerWins()    } else if (userThrow == 'paper') {      opponentThrow == 'rock' ? userWins() : computerWins()    } else {      opponentThrow == 'paper' ? userWins() : computerWins()    }  }    if (score.user === 5) {    alert('You won the first to 5!')    resetScore()  }    if (score.computer === 5) {    alert('You lost the first to 5!')    resetScore()  }}// Attach event handlers to each buttonbuttons.forEach(button => {  button.addEventListener('click', e => {    // Assign data attribute to variable    let userThrow = e.target.dataset.type    e.preventDefault()    // Pass user selection to rpsMatch    rpsMatch(userThrow)  })})`
• `<div class="user">User Score: <span class="score">0</span></div><div class="computer">Computer Score: <span class="score">0</span></div><button data-type="rock">Rock</button><button data-type="paper">Paper</button><button data-type="scissors">Scissors</button><div class="userThrow"></div><div class="opponentThrow"></div><div class="result"></div>`
• Adam Fratino - vote: 0
• I would not use
`prompt`
but HTML buttons to get the user's input. That way they don't have to type, just click.
• 以下是您可以做到的：
• `//declaring an array with weapon of choiceconst weaponArray = ["rock", "paper", "scissors"];const players = ["tie", "you", "computer"];const points = [0, 0, 0]; // tie, player, computerconst human = document.querySelector('#human');const computer = document.querySelector('#computer');const winner = document.querySelector('#winner');const humanScore = document.querySelector('#humanScore');const computerScore = document.querySelector('#computerScore');// Respond to inputdocument.querySelector("#buttons").onclick = function(e) {    const playerChoice = +e.target.value; // 0, 1 or 2    human.textContent = weaponArray[playerChoice];    // selects a random index from array to represent computer choice    const computerChoice = Math.floor(Math.random() * weaponArray.length); // 0, 1 or 2    computer.textContent = weaponArray[computerChoice];    // Determine result    const result = (playerChoice + 3 - computerChoice) % 3; // 0 = tie, 1 = player win, 2 = computer win    winner.textContent = players[result];    // add point to the relevant winner. Winner 0 represents the ties - they don't really count    points[result]++;     humanScore.textContent = points[1];    computerScore.textContent = points[2];    if (result && points[result] >= 5) {        alert("Game over. " + players[result] + " won");        location.reload();    }}`
• `Please make your choice:<br><div id="buttons">    <button value="0">rock</button> <button value="1">paper</button> <button value="2">scissors</button><br></div>Your weapon: <span id="human"></span><br>Computer's weapon: <span id="computer"></span><br>Winner: <span id="winner"></span><br>Your score: <span id="humanScore"></span><br>Computer's score: <span id="computerScore"></span><br>`

### 使用nodejs和mongodb进行前端搜索

Frontend search with nodejs and mongodbCaleb 问题: 我今天刚开始学习mongodb，我有一段代码可以用来查询我的数据库和搜索地址：“Park Lane 38”。这是代码，这是结果：...

### 应该如何使用kotlin将findViewById传递数据从活动页面写入片段页面

How should write the findViewById pass data to Fragment page from Activity page using kotlinMIN LEE 问题: //这是我的活动页面覆盖...

### 脚本1 linux中的crear usuarios和demás

Script 1 de crear usuarios y demás en linuxMaría Isabel De la Osa Rocha 问题: Cómo se haría el script del usuario porq...

### C++：泛型&gt&gt；如何为一个通用函数定义多个模板解题，该函数充当静态实例创建者

C++:Generics >> How to define several template deklarations for a generic function, which serves as an static inst...

### 三js如何向FBX模型添加多个没有蒙皮的Mixamo动画？

Three.js how to add multiple Mixamo animations without skin to an FBX model?Anye 问题: I'm trying to create a game whe...

### Visual Studio GitHub链接到一个陌生人帐户

Visual Studio GitHub is linked to a stranger accountAhmed Khaldoon 问题: 我从VisualStudio2022（我们称之为divice a）中创建了一个新的私有re...

#### 发表评论

◎欢迎参与讨论，请在这里发表您的看法和观点。