0

I create new array and add to her specific values. I add in first index and first index has value, but if I add in second or more index, last indexes are empty and I don't know why. Here my code.

const inputs = [...document.querySelectorAll('.input')];

let timeout = null;

inputs.forEach((input, index) => {
  input.addEventListener('keyup', () => {
    clearTimeout(timeout);

    let inputValue = Number(input.value);

    timeout = setTimeout(() => {
      if (index !== 1) {
        let arr = [];

        if (index === 0) {
          arr[0] = inputValue;
        } else if (index === 2) {
          arr[1] = inputValue;
        } else if (index === 3) {
          arr[2] = inputValue;
        } else if (index === 4) {
          arr[3] = inputValue;
        }

        console.log(arr);
      }
    }, 1000);
  });
});
2
  • 1
    arr needs to be a global variable. Commented Dec 14, 2020 at 21:50
  • it is working, thanks dude I forgot about global variable 🙄 Commented Dec 14, 2020 at 22:03

1 Answer 1

2

Use of the "push" array function. Example:

const inputs = [...document.querySelectorAll('.input')];

let timeout = null;
let arr = [];

inputs.forEach((input, index) => {
  input.addEventListener('keyup', () => {
    clearTimeout(timeout);
    
    let inputValue = Number(input.value);
    timeout = setTimeout(() => {
        arr.push(inputValue);
        console.log(arr);      
    }, 1000);
  });
});
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.