push()在javascript中不起作用 [英] push() not working in javascript
本文介绍了push()在javascript中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:控制台中的Uncaught TypeError: Object #<Object> has no method 'push'
.
推荐答案
更改存储项目id(Cart),然后重试,看起来以前存储在"Cart" ID下的项目不是json数组,因为注释部分建议使用@ dc5
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:尝试以下 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
Javascript
//TODO: move from globals
var 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);
});
});
function addToCart(item){
//by @slebetman
var items = JSON.parse(localStorage.getItem(storageName));
if (! (items instanceof Array) ) {
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 index
function getItemIndexById(items, id){
for(var i = 0; i < items.length; i++){
if(items[i].ID == id){
return i;
}
}
return false;
}
这篇关于push()在javascript中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文