Skip to content Skip to sidebar Skip to footer

Array Value Overwrites Instead Of Retaining Old Value - Javascript

This is what I want. User enters a numerical input. If he enters 2, the code prompts to enter two player names. The player names are stored in an array. There is a 'next' button

Solution 1:

Your for-loop always starts from 0 for the same tempArr (initialized once outside the addValue method), hence it overwrites the previous entries.

for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

You need to initialize the tempArr array inside the addValue method.

Demo

var loopThroughAllNames = [];
varTotalNumOfPlayers = prompt("Enter The Total Number Of Players!");
addValue();

functionaddValue () 
{
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name");
  }
  loopThroughAllNames.push(tempArr);  
  console.log( loopThroughAllNames );
}

varNextList = document.querySelector("#NextList");
NextList.addEventListener("click", function() {
  addValue( );
});
<buttonid="NextList">Next list</button>

Solution 2:

Check below link

JsFiddle

varTotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var loopThroughAllNames = [];
varNextList = document.querySelector("#NextList");

addValue();

functionaddValue() {
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name " + (i + 1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();
  document.write(JSON.stringify(loopThroughAllNames));
});
<buttonid="NextList">Next list</button>

Solution 3:

I am creating an array of arrays to insert names. tempArr is declared as empty inside addValue and later pushed into global array allnames

varTotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = newArray(newArray());
varNextList = document.querySelector("#NextList");
var allnames = [];

addValue();

functionaddValue() {
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
  allnames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();
  console.log(allnames)
});
<buttonid="NextList">Next list</button>

Post a Comment for "Array Value Overwrites Instead Of Retaining Old Value - Javascript"