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()).
Related
My game has two players that get random numbers, and the person who has the bigger number gets 1 "win". My while loop is for the "auto-roll" button, and instead of clicking "roll dice" each time, auto-roll will do it for you until one player has wins == game limit # (bestof.value). No matter where I put my setInterval it increases by a bunch at a time. If bestof.value = 10 then each interval displays at least 10 wins for one player at a time.
checkBox.checked = input checkmark that enables auto-roll feature. So this setInterval will only be active while the auto-roll loop is active.
Anyways, what am I doing wrong?
button.addEventListener("click", myFunction);
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
screenID.innerHTML = random;
screenIDD.innerHTML = random2;
if (random > random2){
winNumber.innerHTML = ++a;
} else if(random2 > random){
winNumba1.innerHTML = ++b;
} else {
console.log("Draw");
}
if (a > b){
winNumber.style.color = 'white';
winNumba1.style.color = 'black';
} else if(b > a){
winNumba1.style.color = 'white';
winNumber.style.color = 'black';
} else {
winNumber.style.color = 'black';
winNumba1.style.color = 'black';
}
if (checkBox.checked){
setInterval(myFunction, 2000)
while(a < bestof.value && b < bestof.value){
myFunction();
}};
if (winNumba1.innerHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumba1 wins!');
} else if (winNumber.innterHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumber wins!');
} else {}
};
I wrote a simplified js only version of your game here since I don't have html at hand, but I am sure you can adjust it to your environment.
Main difference: I check if someone won and use return to stop the function
If no one won and autoplay is activated I autoplay after 500ms again.
let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
console.log("New Round " + random + " vs " + random2)
if (random > random2) {
playerA++
} else if (random2 > random) {
playerB++
} else {
console.log("Draw");
}
if (playerA > playerB) {
console.log("a is winning")
} else if (playerB > playerA) {
console.log("b is winning")
} else {
console.log("There has been a draw")
}
if (playerA == bestOf) {
console.log('A won');
return
} else if (playerB == bestOf) {
console.log('B won');
return
}
if (autoPlay) {
setTimeout(myFunction, 500)
};
};
myFunction()
I aam trying to create a math game for kids that will ask the player his name and the player to select the level he is playing ,how will I display random math questions from my javascript to my html page but the numbers to be generated are not showing just the signs, this is my script i linked it to my html externally.
here's my code:
var pageName = location.pathname.split("/").slice(-1);
window.addEventListener('load', function () {
alert(pageName);
randomOpr();
pageAction();
});
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
function pageAction() {
if (pageName == "level1.html") {
num1.innerHTML = Math.floor(Math.random() * 20 + 1);
num2.innerHTML = Math.floor(Math.random() * 20 + 1);
} else if (pageName == "level2.html") {
num1.innerHTML = Math.floor(Math.random() * 30 + 21);
num2.innerHTML = Math.floor(Math.random() * 30 + 21);
} else if (pageName == "level3.html") {
num1.innerHTML = Math.floor(Math.random() * 50 + 51);
num2.innerHTML = Math.floor(Math.random() * 50 + 51);
}
}
var operators = ['+', '-', '*', '/']
var selectedOperator = Math.floor(Math.random() * operators.length);
function randomOpr() {
var operator = document.getElementById("opr");
alert((operator).value);
operator.innerHTML = operators[selectedOperator];
}
function checkMath() {
var num1 = parseInt(document.getElementById("num1").innerHTML, 10);
var num2 = parseInt(document.getElementById("num2").innerHTML, 10);
var answer = parseInt(document.getElementById("answer").value, 10);
if (operators[selectedOperator] == "+") {
if (answer === num1 + num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 + num2));
}
} else if (operators[selectedOperator].sign == "-") {
if (answer === num1 - num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 - num2));
}
} else if (operators[selectedOperator].sign == "*") {
if (answer === num1 - num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 * num2));
}
} else if (operators[selectedOperator].sign == "/") {
if (answer === num1 - num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 / num2));
}
}
document.getElementById("answer").value = "";
randomNum();
}
Cleaned up the code as suggested in the comments.
No need to get the numbers in the question a second time (already have them when generated).
No need to repeat the answer check and alert code for each operator.
What was 'sign' in 'operators[selectedOperator].sign' in three of the four checks? - removed.
What was randomNum()? - removed.
I'd also check values for the divide questions...
<body>
<div id="num1"></div>
<div id="opr"></div>
<div id="num2"></div>
<div>
<input type=text id="answer">
</div>
<button id="btnAnswer">Check answer</button>
<script>
$(function () {
$("#btnAnswer").click(checkMath)
});
// Set up re-usable variables first.
var pageName = location.pathname.split("/").slice(-1);
var operators = ['+', '-', '*', '/']
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var answerInput = document.getElementById("answer");
var operator = document.getElementById("opr");
// The values of the numbers to use in the question, current Operator, and calculated answer.
var leftNumber = 0;
var rightNumber = 0;
var selectedOperator = "";
var answer = 0;
window.addEventListener('load', function () {
alert(pageName);
pageAction();
});
function pageAction() {
// Use a switch to perform the check on the level, then set the multiplier.
var multiplier = 0;
switch (pageName) {
case "level1.html":
multiplier = 20;
break;
case "level2.html":
multiplier = 30;
break;
case "level3.html":
multiplier = 50;
break;
default:
multiplier = 20;
break;
}
// Generate the numbers, set them on the page, and get a random Operator.
leftNumber = Math.floor(Math.random() * multiplier + 1);
rightNumber = Math.floor(Math.random() * multiplier + 1);
num1.innerText = leftNumber;
num2.innerText = rightNumber;
answerInput.value = "";
randomOpr();
// Calculate the answer for later use.
switch (selectedOperator) {
case "+":
answer = leftNumber + rightNumber;
break;
case "-":
answer = leftNumber - rightNumber;
break;
case "*":
answer = leftNumber * rightNumber;
break;
case "/":
answer = leftNumber / rightNumber;
break;
default:
answer = leftNumber + rightNumber;
break;
}
}
function randomOpr() {
// Set the current Operator, update the page control.
selectedOperator = operators[Math.floor(Math.random() * operators.length)];
operator.innerText = selectedOperator;
alert((operator).innerText);
}
function checkMath() {
// Check submitted answer against the calculated one, then re-run for another question.
var submittedAnswer = parseInt(answerInput.value, 10);
if (submittedAnswer === answer) {
alert("your answer is correct");
} else {
alert(submittedAnswer + " is incorrect, correct answer is " + answer);
}
pageAction();
}
</script>
</body>
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>
In the code below, when I set the userDoor variable to the prompted user input, the user input attaches to the variable. I know this because the value shows up in the console.log statement just below the variable declaration.
However, the variables revealDoor and offerDoor, which are set based on the userInput variable, act wonky in ways that suggest the variable didn't "catch" the value. (Wonky: easier to demonstrate than explain. please run the code below. UserDoor, revealDoor, and offerDoor should all be different numbers in the range of 1-3. Some of the time, revealDoor === userDoor. This should never happen. ).
Interestingly, the program works fine when I set userDoor directly to an integer--see commented debug line.
Why would the userInput variable show the right value in the console but not seem to catch in the rest of the program?
(This program, by the way, is meant to illustrate the monty hall paradox
alert("There are 3 doors. Behind two of them are DEATH and DOOM. Behind the other is a BIG TASTY SAUSAGE.");
var yWin = 0;
var yLoss = 0;
var nWin = 0;
var nLoss = 0;
while(true){ //noprotect
var userDoor = prompt("choose door: 1, 2, or 3");
//var userDoor = 1 //debug
console.log('UD: ' + userDoor);
var prizeDoor = randomRange(1,3);
console.log('PD: ' + prizeDoor);
var revealDoor = (function(){
var revealDoor = prizeDoor;
if (prizeDoor === userDoor) {
while (revealDoor === prizeDoor) {
revealDoor = randomRange(1,3);
}
return revealDoor;
}
else {
while (revealDoor === prizeDoor || revealDoor === userDoor){
revealDoor = randomRange(1,3);
}
return revealDoor;
}
})();
console.log('RD: ' + revealDoor);
var offerDoor = (function(){
var offerDoor = prizeDoor;
while(offerDoor === revealDoor || offerDoor === userDoor){
offerDoor = randomRange(1,3);
}
return offerDoor;
})();
console.log('OD: ' + offerDoor);
var choice = prompt("You chose door " + userDoor + ". Behind door " + revealDoor + ", I reveal DEATH AND DOOM. I would like to offer you the chance to change your choice to " + offerDoor + ". Do you accept--y/n?");
if(choice === "y"){
userDoor = offerDoor;
}
var result = (function(){
var result;
if(userDoor === prizeDoor){
alert("YOU FOUND THE PRIZE!");
result = 'w';
}
else {
alert("You chose DEATH AND DOOM!");
result = 'l';
}
return result;
})();
//Analytics:
switch(result){
case 'w':
if(choice === 'y'){
yWin++;
}
else {
nWin++;
}
break;
case 'l':
if(choice === 'y'){
yLoss++;
}
else {
nLoss++;
}
break;
}
var done = prompt("Are you Done? y/n");
if(done === "y"){
break;
}
}
function randomRange(min, max) {
return Math.floor(Math.random () * (max - min +1)) + 1;
}
var totalSamples = yWin + nWin + yLoss + nLoss;
var yChoices = yWin + yLoss;
var nChoices = nWin + nLoss;
console.log('With a sample set of ' + totalSamples);
console.log('You chose to change ' + (yChoices/nChoices * 100) + '% of the time.');
console.log('When you\'ve chosen to change, you\'ve won ' + (yWin/yChoices * 100) + '% of the time.');
console.log('When you\'ve chosen to stay, you\'ve won ' + (nWin/nChoices * 100) + '% of the time.');
var userDoor = prompt("choose door: 1,2, or 3")) * 1
Its better 2 use radio button for this
The problem is that prompt() returns a string. Which means any '===' comparisons are returning undefined. I need to convert the returned string to a number using Number().
var userDoor = Number(prompt("choose door: 1,2, or 3"))
Use
var done = confirm("Are you Done? y/n");
if (done) break;
Instead of d prompt confirmation
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