Last item in for loop executes multiple times in Javascript - javascript

I'm making a JavaScript/jQuery version of a dice game my buddies and I play. Here's a 3 player version of the game:
http://codepen.io/jwnardini/pen/jmygqd
I'm trying to make a version of the game where the user can select how many players are playing, and have the game function in the same way:
http://codepen.io/jwnardini/pen/ZKLVqW
Every time the "Go" button is pressed, it's supposed to move on to the next person's turn, and I use a modular operator if condition in a for loop to check whose turn it is, so i can perform a specific action on their turn.
var turn = 0;
$(".goButton").click(function() {
turn = turn + 1;
var playerCount = $('#input-number').val();
for (i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
});
This works great for every player I've created, except the last one (player# playerCount). This is because playerCount % playerCount = 0, and i is never 0, so the last player is always skipped.
I tried to work around this with an else statement for when turn % playerCount = 0 :
var turn = 0;
$(".goButton").click(function() {
turn = turn + 1;
var playerCount = $('#input-number').val();
for (i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
} else if (turn % playerCount == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
}
});
However, when I reach player# playerCount's turn, I get playerCount times "hi!" appended. For example, for 5 players, this is the output in browser:
Player 1
$3Hi!
Player 2
$3Hi!
Player 3
$3Hi!
Player 4
$3Hi!
Player 5
$3Hi!Hi!Hi!Hi!Hi!
Is this a classic "off by 1" error on my part? Or is my else statement flawed in some way?

The problem is your loop, when you iterate over playerCount and try to get the class name to append to.
Instead of the entire loop, try to do the following:
var m = turn % playerCount;
if (m==0) {m = playerCount};
$(".player" + m + "dollars").append("Hi!");

take out the 4th player condition outside the loop. the problem is when turn ==playercount, u dont have to enter the loop because that condiiotn is independant of i and will always be true hence hgetting executed times.
for (var i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
if (turn % playerCount == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
here is the code working code snippet :
var turn = 0;
var pot = 0;
$("form").submit(function(event){
var i = 0
var playerCount = $('#input-number').val();
var dollarCounts = [];
$(".players").empty();
for (var i=1; i <= playerCount; i++) {
var player= "player";
player = player + i.toString();
$(".players").append(
'<div class="player-wrap"><div class="player' + i.toString() + ' clearable">Player '
+ i +
'</div>$<span class="' + player + 'dollars clearable"></span><br><br><br></div>');
dollarCounts[i] = 3;
$("." + player + "dollars").empty().append(dollarCounts[i]);
}
event.preventDefault();
});
//TURN
$(".goButton").click(function() {
turn = turn + 1;
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
var dice3 = Math.floor(Math.random() * 6) + 1;
$(".turn").empty().append(turn);
//Print "Left", "Right", "Center"
if (dice1 == 1) {
$(".d1").empty().append("LEFT");
}
if (dice2 == 1) {
$(".d2").empty().append("LEFT");
}
if (dice3 == 1) {
$(".d3").empty().append("LEFT");
}
if (dice1 == 2) {
$(".d1").empty().append("RIGHT");
}
if (dice2 == 2) {
$(".d2").empty().append("RIGHT");
}
if (dice3 == 2) {
$(".d3").empty().append("RIGHT");
}
if (dice1 == 3) {
$(".d1").empty().append("CENTER");
}
if (dice2 == 3) {
$(".d2").empty().append("CENTER");
}
if (dice3 == 3) {
$(".d3").empty().append("CENTER");
}
if (dice1 == 4 || dice1 == 5 || dice1 == 6) {
$(".d1").empty().append("SAFE");
}
if (dice2 == 4 || dice2 == 5 || dice2 == 6) {
$(".d2").empty().append("SAFE");
}
if (dice3 == 4 || dice3 == 5 || dice3 == 6) {
$(".d3").empty().append("SAFE");
}
var playerCount = $('#input-number').val();
for (var i=1;i < playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
if (turn % i == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
});
//RESET
$(".resetButton").click(function() {
turn = 0;
pot = 0;
$(".players").empty();
var playerCount = 0;
var dollarCounts = [];
$(".turn").empty().append(turn);
$(".pot").empty().append(pot);
$(".d1").empty();
$(".d2").empty();
$(".d3").empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="start-form">
<label for="input-number">Number of players:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Set Player Count</button>
</form>
<button class="goButton" type="submit">Go</button>
<button class="resetButton" type="submit">Reset</button>
<br><br>
<div class="players"></div>
<h1>Turn count: <span class="turn"></span></h1>
<h2>Rolls:
<span class="d1"></span>
<span class="d2"></span>
<span class="d3"></span>
</h2>
<br>
<br>
<br>
<br>
<br>
<h1>POT</h1>
<div class="pot"></div>

Related

Printing For Loop Is One Number Off Each Time

I'm playing around with some HTML and Javascript. I'm trying to print out 100 numbers on a screen after I press a button on a webpage. I can get the numbers to print on the screen but when I want to replace a number with a string like "Apple" if the number is divisible by 5. The code is below:
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i + 1) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The output is always off by one element so it would print "5" and then the next line would be "Apple" instead of replacing "5" with "Apple" and then printing "6"
Here is the output:
0
Pineapple
2
3
Pine
5
Apple
Pine
8
9
Pine
Apple
12
Pine
14
15
Pineapple
17
18
Pine
20
You are printing i+1, instead of i.
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i ) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The trouble is in the starting point of your for loop, where you initialize with -1 instead of 0. While you use (i + 1) at the end when you print a number, which is why it causes your results to be one number off.
Use for(var i = 0; i <= 20; i++) instead of for (var i = -1; i < 20; i++) when you want to loop 20 times.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = 0; i <= 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + i + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
Using this code I was able to replace 5 with Apple.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++){
if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br>';
} else{
myHTML += '<span class="test">' + i + '</span><br>'
}
}
wrapper.innerHTML = myHTML
}
testFunction();
<div id="Test"></div>
Use this snippet to follow what exactly happens within your loop. It should give you some clues.
const log = Logger();
testFunction();
function testFunction() {
for (let i = -1; i < 20; i += 1) {
if (i % 5 == 0 && i % 3 == 0) {
log(`${i} % 5 === 0 && ${i} % 3 === 0 => Pineapple`);
} else if (i % 5 == 0) {
log(`${i} % 5 === 0 => Apple` );
} else if (i % 3 == 0) {
log(`${i} % 3 === 0 => Pine`);
} else {
log(`i = ${i}, i + 1 = ${i + 1}`);
}
}
}
function Logger() {
let logEl;
if (typeof window === "object") {
logEl = document.querySelector("#log") || (() => {
document.body.appendChild(Object.assign( document.createElement('pre'), { id: "log" }) );
return document.querySelector("#log");
})();
return (...logLines) => logLines.forEach(s => logEl.textContent += `${s}\n`);
} else {
return (...logLines) => logLines.forEach(ll => console.log(`* `, ll));
}
}

Compare two array elements using if() statment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code bellow works fine, though as u can see, everything is hand wrote and if i want to push something to that arrays i will have to change whole code.
working example:
for (var s = 0; s < myButtons.length; s++) {
if (
(myButtons[s].className == "1" && colorIndex[0] > 1)
||
(myButtons[s].className == "2" && colorIndex[1] > 1)
||
(myButtons[s].className == "3" && colorIndex[2] > 1)
||
(myButtons[s].className == "4" && colorIndex[3] > 1)
||
(myButtons[s].className == "5" && colorIndex[4] > 1)
||
(myButtons[s].className == "6" && colorIndex[5] > 1)
) {continue;}
alert("things need to be done")
}
the best solution came to my mind(not working one):
for (var s = 0; s < myButtons.length; s++) {
for (var i = 0; i < colorIndex.length; i++) {
if ((myButtons[s].className == (i + 1) && colorIndex[i] > 1)) {
continue;
}
alert("things need to be done")
}
}
So what i want is: to check if all elements of array myButtons.classname==variable from cycle && colorIndex[variable from cycle]>1 OR same thing again but on next step
working code for the first algorithm
const colorIndex = []
colorIndex[0] = 201
colorIndex[1] = 30002
colorIndex[19] = -25
colorIndex[3] = 89
colorIndex[-7] = 89
colorIndex[-9] = -26
const myButtons = [...document.querySelectorAll("button")]
for (var s = 0; s < myButtons.length; s++)
{
if ( (myButtons[s].className == "1" && colorIndex[0] > 1)
|| (myButtons[s].className == "2" && colorIndex[1] > 1)
|| (myButtons[s].className == "3" && colorIndex[2] > 1)
|| (myButtons[s].className == "4" && colorIndex[3] > 1)
|| (myButtons[s].className == "5" && colorIndex[4] > 1)
|| (myButtons[s].className == "6" && colorIndex[5] > 1)
)
{ continue }
alert("things need to be done")
}
console.log('test ending')
<button class="1">1</button>
<button class="2">2</button>
<button class="4">3</button>
<button class="4">4</button>
<button class="4">5</button>
<button class="4">6</button>
<button class="4">7</button>
<button class="2">8</button>
<button class="4">9</button>
Here a pretty short and less hard coded version of the original code
var myButtons = document.querySelectorAll("button");
var colorIndex = [0, 1, 2, 0, 2, 1];
for (var index = 0; index < myButtons.length; index++) {
if (myButtons[index].className == String(index + 1)
&& colorIndex[myButtons[index].className - 1] > 1) continue;
console.log("Button at index '" + index + "' needs to get fixed");
}
<button class="1">1</button>
<button class="2">2</button>
<button class="3">3</button>
<button class="4">4</button>
<button class="5">5</button>
<button class="6">6</button>
Full code attempt:
// Create Buttons Start
var buttonDom = document.getElementById("a1");
var buttonList = [],
buttonCount = 12;
while (buttonList.length < buttonCount) {
var newInput = document.createElement("input");
newInput.type = "button";
buttonList.push(newInput);
buttonDom.appendChild(newInput);
}
var randomList1 = [];
while (randomList1.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList1.indexOf(random) === -1) randomList1.push(random);
}
var randomList2 = [];
while (randomList2.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList2.indexOf(random) === -1) randomList2.push(random);
}
randomList1.forEach((random, index) => buttonList[index].setAttribute("class", random));
randomList2.forEach((random, index) => buttonList[index + buttonCount / 2].setAttribute("class", random));
// Game Start
var myButtons = document.querySelectorAll("input[type='button']");
var click = 1;
var colorIndex = "0".repeat(6).split("").map(Number);
var color = ["red", "blue", "green", "black", "gold", "grey"];
myButtons.forEach(button => button.addEventListener("click", game));
function clickTrun() {
click = !click | 0;
}
function win() {
if (colorIndex.every(i => i == 2)) {
alert("YOU WON mdfker!");
location.reload();
}
}
function resetColorIndex() {
if (click === 1) {
colorIndex = colorIndex.map(function(colorValue) {
return colorValue < 2 ? 0 : colorValue;
});
}
}
function mainGameRules() {
setTimeout(function() {
resetColorIndex();
if (click === 1) {
myButtons.forEach(function(button) {
if (colorIndex[button.className - 1] > 1) return;
button.setAttribute("style", "background-color: none;");
button.disabled = false;
});
}
}, 700);
}
function game() {
this.disabled = true;
var index = this.className - 1;
if (index in colorIndex) {
this.setAttribute("style", "background-color:" + color[index]);
colorIndex[index]++;
mainGameRules();
clickTrun();
}
win();
}
<div id="a1">
</div>
You just need to formulate what you want to do and express it in code. Without sticking to concrete index, try to figure out how any possible index corresponds to particular color. Looking at your example you want to take className for every button, subtract 1 and take color from colorIndex and do something if that color is less than or equal to 1
for (let i = 0; i < myButtons.length; i++) {
// className for current button
const className = myButtons[i].className
// parse it into number
const num = Number(className)
// if number is valid, take element from colorIndex at number-1 position
// and see if that's not bigger than 1
if (num && colorIndex[num - 1] <= 1) {
console.log('things need to be done for index ' + i)
}
}
but my suggestion would be to reconsider your existing setup with myButtons and colorIndex into something more sophisticated

Javascript/HTML won't enter switch case other than default

My task was to try and code the game of Pig. I am trying to have the code use a switch statement to determine which chunk of code to follow but it is skipping case 1 and case 2 and going directly to the default case. The roll.score is coming from this Javascript file:
function Dice(d1, d2){ //d1 = die 1 d2 = die 2
this.d1 = d1?d1:parseInt(Math.random()*6 + 1);
this.d2 = d2?d2:parseInt(Math.random()*6 + 1);
}
Dice.prototype.score = function(){ //d1 = die 1 d2 = die 2
if(this.d1 == 1 || this.d2 == 1){
return 1; //return score 0 for turn
}else if(this.d1 == 1 && this.d2 == 1){
return 2; //return 13 as code to reset score to 0
}else
return parseInt(this.d1 + this.d2);
}
Dice.prototype.toString = function(){
return "Rolled " + this.d1 + " and " + this.d2;
}
What it is supposed to do is return either 1, 2, or whatever the 2 number added together are. Like I mentioned above, no matter what the roll.score() returns, the switch statement always goes to the default case.
var again = true;
do {
var roll = new Dice(parseInt(Math.random() * 6 + 1), parseInt(Math.random() * 6 + 1));
window.alert(roll.toString());
turnCounter++;
switch (roll.score) {
case 1: // 1 die = 1
playerScore = roll.score();
again = false;
rollCounter++;
turnCounter++;
document.write("Enters case 1");
break;
case 2: //2 = snake eyes
playerTotal = 0;
playerScore = 0;
again = false;
rollCounter++;
turnCounter++;
break;
default:
playerScore += roll.score();
rollCounter++;
displayScore();
document.write(roll.score() + "<br/>");
var rollAgain = window.prompt("Do you want to roll again?(Y/N)");
if (rollAgain.toUpperCase() === "N") {
again = false;
playerTotal += playerScore;
displayScore();
turnCounter++;
if (playerScore > highScore)
highScore = playerScore;
}
break;
}
rollCounter++;
}while (again);
switch (roll.score) { is not the same as switch (roll.score()) {
roll.score is a function, whereas you want to switch on the result on the returned result (roll.score()).

Instantly change button when value reaches 0 javascript

When I clicking the button the user HP goes down till 0 and then button changes. But what happens more is, when the userHealth reaches zero the button did not change. You have to click one more time to button change. How to solve this ?
JS:
$(".attBtn").click(function() {
var userId = 4;
var attackdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var userdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var minimum = 0;
if(userHealth == 0){
info.innerHTML = '<strong>'+user.textContent+'</strong> have been defeated.';
attackBtn.css("backgroundColor", "blue");
attackBtn.css("border", "none");
innerAttBtn.innerHTML = "Get the reward <img src="+"/img/chest2.png"+"/> ";
return false;
}else if(attackerHealth == 0){
info.innerHTML = '<strong>You</strong> have been defeated.';
}else if(attackerHealth == 0 && userHealth == 0){
info.innerHTML = '<strong>DRAW FIGHT</strong>';
}else{
userHealth -= attackdmg;
attackerHealth -= userdmg;
document.getElementById('attackerBar').setAttribute("style","width:"+attackerHealth+"%");
document.getElementById('userBar').setAttribute("style","width:"+userHealth+"%");
$.ajax("/arena/fight-user/"+userId+"/attack/"+attackdmg+"/"+userdmg,
{
});
if(userHealth < 0){userHealth = minimum;}
if(attackerHealth < 0){attackerHealth = minimum;}
userHp.innerHTML = '<strong>'+userHealth+'</strong>';
attackerHp.innerHTML = '<strong>'+attackerHealth+'</strong>';
info.innerHTML = '<strong>' +user.textContent+'</strong>' +' hit <strong>You</strong> with ' +userdmg+' dmg <br> ' + '<strong>You</strong> hit '
+'<strong>'+user.textContent+'</strong>'+ ' with '+ attackdmg +' dmg';
}
});
there is a logical flaw.
The reason, why you have to click once more, is because you declare what should happen at 0 HP before the HP gets actually to zero.
The solution
put this
userHealth -= attackdmg;
attackerHealth -= userdmg;
if(userHealth < 0){userHealth = minimum;}
if(attackerHealth < 0){attackerHealth = minimum;}
before this
if(userHealth == 0){
...

Finding out how many times an array element appears

I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>
Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.
With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3
Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..
When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;
Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}
Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5

Categories