1

Im trying to collect user input into array but everytime i do the previous is being replaced.Here is my code

  let inputValue = input.value;
  let inputArray = [];
  inputArray.push(inputValue);
  console.log(inputArray);
2
  • Move let inputArray = []; , outside the function. It should be initialized only once. Commented May 6, 2018 at 8:49
  • everytime you are redeclaring the array as []. Only push within the function or event handler Commented May 6, 2018 at 8:49

1 Answer 1

3

Your declaring your inputArray as empty all the time, if you have that code inside a function scope like this:

function collectUserInput() {
  let inputValue = input.value;
  let inputArray = [];
  inputArray.push(inputValue);
  console.log(inputArray);
}

you need to declare the inputArray outside the function so evertyme you call the ollectUserInput you add one more input to the pre-existing array, like this:

let inputArray = [];

function collectUserInput() {
  let inputValue = input.value;
  inputArray.push(inputValue);
  console.log(inputArray);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.