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?

asked Dec 17, 2013 at 12:34

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

answered Dec 17, 2013 at 12:35
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.

answered Dec 17, 2013 at 12:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.