【发布时间】:2014-07-31 01:25:52
【问题描述】:
这是我的数组的结构:
[{"stockCode":"PALLET CARDS","quantity":"2"},
{"stockCode":"PALLET CARDS","quantity":"3"},
{"stockCode":"CBL202659/A","quantity":"1"},
{"stockCode":"CBL201764","quantity":"3"}]
当点击订单button 时,我想检查stockCode 是否存在于这个array 中。但是,每次我这样做时,我都会返回 -1。
这是我检查stockCode的代码:
$(".orderBtn").click(function(event){
//Check to ensure quantity > 0
if(quantity == 0){
console.log("Quantity must be greater than 0")
}else{//It is so continue
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
//Order Item (contains stockCode and Quantity) - Can add whatever data I like here
var orderItem = {
'stockCode' : stockCode,
'quantity' : quantity
};
//Check if cookie exists
if($.cookie('order_cookie') === undefined){
console.log("Creating new cookie");
//Add object to the Array
productArray.push(orderItem);
}else{//Already exists
console.log("Updating the cookie")
productArray = JSON.parse($.cookie('order_cookie'));
//Check if the item already exists in the Cookie and update qty
if(productArray.indexOf(stockCode)!= -1){
//Get the original item and update
console.log("UPDATING EXISTING ENTRY " + productArray.indexOf("PALLET CARDS"));
}
else{
console.log("ADDING NEW ENTRY ");
//Insert the item into the Array
//productArray.push(orderItem);
}
}
}
//Update the Cookie
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
//Testing output of Cookie
console.log($.cookie('order_cookie'));
});
当用户点击订单button时,我得到一个stockCode的引用:
var stockCode = $(this).closest('li').find('.stock_code').html();
我想检查这个 stockCode 是否已经在 array 中,如果是,那么我不会添加新条目,而是更新现有条目。
【问题讨论】:
-
duplicate 之前有人问过这个问题...您不能对对象数组执行直接 indexOf 。您必须比较数组中的每个元素。
-
问题仍未得到解答?
标签: javascript jquery arrays