1

I have an empty array and I want to insert content in that.

This the code that I use:

document.addEventListener('keypress', function(e) {

    var myArr = [];
    var newContent = myArr.push(e.keyCode);
    console.log(myArr);

});

When I press the keyboard, I want to store all keyCode pressed into one Array without deleting the existing values of that Array. Currently, it stores one value of the first press and when I press again, it replaces this value with a new one.

I want to have this form: ["value 1", "value 2", "value 3", ...], but what I get is ["value 1"]...["new value"] etc...

What am I doing wrong here?

2 Answers 2

4

Declare the array myArr outside the scope because each time when you do a keypress, myArr variable is getting initialized.

var myArr = [];
document.addEventListener('keypress', function(e) {
    var newContent = myArr.push(e.keyCode);
    console.log(myArr);

});

Check this JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You are declaring your array i.e. var myArr. So every time it is creating new array. So declare outside of current block.

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.