Push() Not Working In Javascript
Solution 1:
Change storage item id(Cart) and try again, looks like previously stored item under "Cart" id is not json array as @dc5 suggested in comment section
UPD: Try this http://jsfiddle.net/vJkBQ/4/
HTML
<div id='cart'></div>
<input type="button"id="add" value="Add To Cart item 1" />
<input type="button"id="add2" value="Add To Cart item 2" />
Javascript
//TODO: move from globalsvar storageName = 'myCART';
$(document).ready(function () {
var item = {
DepartmentID :333,
CategoryID:117,
BrandID:19,
BrandImage:" ",
BrandName:"General",
ID:711
};
var item2 = {
DepartmentID :123,
CategoryID:321,
BrandID:18,
BrandImage:" ",
BrandName:"Common",
ID:712
};
localStorage.clear(storageName);
$('#add').click(function(){
addToCart(item);
});
$('#add2').click(function(){
addToCart(item2);
});
});
functionaddToCart(item){
//by @slebetman var items = JSON.parse(localStorage.getItem(storageName));
if (! (items instanceofArray) ) {
items = [];
}
var itemIndex = getItemIndexById(items, item.ID);
if(typeof(itemIndex) === 'number'){
items[itemIndex].quantity++;
}
else{
item.quantity = 1;
items.push(item);
}
localStorage.setItem(storageName, JSON.stringify(items));
console.log(localStorage.getItem(storageName));
}
//find search item indexfunctiongetItemIndexById(items, id){
for(var i = 0; i < items.length; i++){
if(items[i].ID == id){
return i;
}
}
returnfalse;
}
Solution 2:
The expression:
JSON.parse(localStorage.getItem(storageName))
is most likely not returning an array. In which case the statement:
var oldStorage = JSON.parse(localStorage.getItem(storageName)) || [];
is insufficient.
What you should do instead is something like this:
var oldStorage = JSON.parse(localStorage.getItem(storageName));
if (! (oldStorage instanceofArray) ) {
oldStorage = [];
}
This is a simple way to detect arrays. There are more advanced methods such as checking for the existance of .length
etc. that detects arrays and array like objects as well as detect arrays in cases where the Array object have been overwritten or works across iframes.
Additional answer:
You've changed the code a lot but the problem is still the same. The line:
if(items!=null) {
is not sufficient to check that items is an array. You should instead do:
if ( items instanceofArray ) {
to make sure that it really is an array.
Also, in the else block:
}else{
console.log('Cart is empty, preparing new cart array');
items.push(item);
The console.log
message says that a new array is being prepared. However it lies as the code doesn't initialize a new array but uses the items
variable as if it was an array. You should instead do this:
}else{
console.log('Cart is empty, preparing new cart array');
items = [];
items.push(item);
Warning:
However, after all that, please heed the the commenters to my question. If you wrote this whole thing from scratch than doing the things I advised would solve all your problems. But if what you're doing is modifying someone else's code then it's probable that Cart
was stored in a different format than what you expected.
Please do console.log(localStorage['Cart'])
before calling JSON.parse
and post your results here. The problem is with your local storage on your browser and cannot usually be reproduced on other people's machines.
Solution 3:
Does
JSON.parse(localStorage.getItem(storageName))
always return an array? If so, the issue is that not all browsers support the push method. You can add use this snippet to add it if it is missing:
if(!Array.prototype.push){
Array.prototype.push=function(x){
this[this.length]=x;
returntrue
}
};
This code is just a start, you can definitely improve it
Solution 4:
You can use you can invoke Array.prototype.push()
on an object using call()
.
JavaScript
functionappendToStorage(storageName, data){
var oldStorage = JSON.parse(localStorage.getItem(storageName)) || [];
Array.prototype.push.call(oldStorage, data);
localStorage.setItem(storageName,JSON.stringify(oldStorage));
}
Solution 5:
JSON.parse
returns an object or null
. So here you don't know if you have an object or an Array.
JSON.parse(localStorage.getItem(storageName)) || [];
You can use this instead:
functionappendToStorage(storageName, data){
var oldStorage = JSON.parse(localStorage.getItem(storageName)) || {};
if (oldStorage != null){
$(oldStorage).extend(data);
localStorage.setItem(storageName,JSON.stringify(oldStorage));
}
}
$.extend() will add your item to another JSON object. Info here
Post a Comment for "Push() Not Working In Javascript"