Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Insert contents into Array Javascript

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?

Upvotes: 1

Views: 79

Answers (2)

Praveen
Praveen

Reputation: 56509

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

Upvotes: 4

Rahul Sahu
Rahul Sahu

Reputation: 284

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

Upvotes: 0

Related Questions