0

What I want to achieve is to stack values that I clicked from a set of numbers. Get the previous storage values, add the new value into storage and then display the new storage values.
DOM storage like sessionStorage and localStorage migh not the right thing to use in this case though you can try it if it works in your technique.

here's the set of numbers to click:
1 2 3 4 5 6 7 8 9

example expected result: (any number you click will stack like these in console)
1
1 5
1 5 2
1 5 2 9

Here's my code:

function logger(input){
//create array container/storage
var storage = [];

//get previous storage values
var previousInput = storage;

//get new input value
var newInput = input;

//add new input value to storage
var newStorageTotal = storage.push(newInput);

//display all values of storage
console.log(storage); 
}


my code displays the numbers that I clicked and but it did not store the values in the storage.

Edit: It works now. here's the updated code for everyone.

//create array container/storage
var storage = [];
function logger(input){

//get previous storage values
var previousInput = storage;

//get new input value
var newInput = input;

//add new input value to storage
var newStorageTotal = storage.push(newInput);

//display all values of storage
console.log(storage); 
}
Glen Draco
  • 13
  • 3
  • Well, duh. You're always creating new empty arrays each time the function is called. – Touffy Apr 15 '15 at 09:50
  • possible duplicate of [Appending to array](http://stackoverflow.com/questions/351409/appending-to-array) – nha Apr 15 '15 at 10:03
  • @Touffy no need to say the word "duh", we're here to learn not to be rude. – Glen Draco Apr 15 '15 at 10:05
  • Not trying to be rude. I wanted to convey that it is an extremely basic thing, way more basic than you seem to assume by mentionning localStorage. I even upvoted it since I think your question is very clear about what you want to achieve and how you're doing it wrong. Don't take it personally. – Touffy Apr 15 '15 at 11:36

1 Answers1

1

You're erasing your array every time:

var storage = [];

That variable needs to be declared in a higher scope such that it's not re-initialised each time the logger() function is called.

Alnitak
  • 334,560
  • 70
  • 407
  • 495