Reputation: 13
I want to eventually write contactList to the page but even though console.log is showing that contactList is properly receiving contacts being pushed from localStorage, its length remains at 1! And when I do try to iterate over contactList to write to the page, it doesn't work as expected and I see undefined where values should be.
var contactList = [];
window.onload = init;
function init(){
var data = window.localStorage.getItem("contacts");
if(data){
myData = JSON.parse(data);
console.log("This is local storage:\n");
console.log(myData);
console.log("This is contact list before I push local storage:\n");
console.log(contactList);
contactList.push(myData);
console.log("This is contact list after I push local storage:\n");
console.log(contactList);
var j = contactList.length;
console.log("This is the length of contact list:\n");
console.log(contactList.length);
}
}
Here's an example of my console window:
This is local storage:
form.js (line 12) [[[Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", lastname="hi", number="hi"}], Object{ firstname="hi", lastname="hi", number="hi"}] form.js (line 13)
This is contact list before I push local storage:
form.js (line 14) [] form.js (line 15)
This is contact list after I push local storage:
form.js (line 17) [[[[Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", lastname="hi", number="hi"}], Object { firstname="hi", > lastname="hi", number="hi"}]] form.js (line 18)
This is the length of contact list:
form.js (line 20) 1
Upvotes: 0
Views: 50
Reputation: 10899
That is the expected outcome with push
. It looks like you want to use concat
.
push
will append whatever the argument is to a new element at the end of the array. If you add a string it will add the string. If you add an array it will add an array...as the last element. It will not flatten the resultant array. On the other hand concat
will concat the two arrays and return a new array. The original array will be unchanged though.
Upvotes: 1
Reputation: 8494
var a = [1]
console.log(a.length) // 0
var b = [2]
var c = a.push(b)
console.log(c) // [1, [2]]
console.log(c.length) // 2
Try using concat():
var a = [1]
console.log(a.length) // 1
var b = [2]
var c = a.concat(b)
console.log(c) // [1, 2] <<< Desired behaviour
console.log(c.length) // 2
Upvotes: 0