Javascript 使用indexOf()检查JS数组中是否存在特定对象
这是我的阵列的结构:Javascript 使用indexOf()检查JS数组中是否存在特定对象,javascript,jquery,arrays,Javascript,Jquery,Arrays,这是我的阵列的结构: [{"stockCode":"PALLET CARDS","quantity":"2"}, {"stockCode":"PALLET CARDS","quantity":"3"}, {"stockCode":"CBL202659/A","quantity":"1"}, {"stockCode":"CBL201764","quantity":"3"}] 单击订单按钮时,我想检查此数组中是否存在库存代码。然而,每次我这样做,我得到-1返回 这是我检查stockCode
[{"stockCode":"PALLET CARDS","quantity":"2"},
{"stockCode":"PALLET CARDS","quantity":"3"},
{"stockCode":"CBL202659/A","quantity":"1"},
{"stockCode":"CBL201764","quantity":"3"}]
单击订单按钮
时,我想检查此数组中是否存在库存代码
。然而,每次我这样做,我得到-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'));
});
当用户单击订单按钮时,我会得到一个对股票代码的引用:
var stockCode = $(this).closest('li').find('.stock_code').html();
我想检查此stockCode是否已在数组中,如果已存在,我将不添加新条目,而是更新现有条目。我认为您需要这样使用:
$.inArray( stockCode, productArray)
更多信息。使用jquerygrep
匹配数组中“stockcode”键等于stockcode的元素
我希望我的回答正确:
function findByStockCode(code, stockCodeArr){
return stockCodeArr.filter(function(elem){
return elem.stockCode == code;
});
}
这当然会给你们一个数组。如果长度大于零,则具有给定代码的元素已在数组中。我认为过滤功能是在ECMA5中添加的,所以IE8可能不支持它
[提及当前浏览器中未实现筛选器的情况下的回退。
无论如何,有一个类似的jQuery函数,其中“this”指的是实际的元素:
function jQueryFindByStockCode(code, stockCodeArr){
return $(stockCodeArr).filter(function(){
return this.stockCode == code;
});
}
编辑:
正如DhruvPathak提到的,$.grep可能是比jQuery的过滤器更合适的解决方案。()
我再次查找了一个性能更好的解决方案(似乎),您可以自己编写它(无论如何,它非常简单):
//用于定义的非空值
函数findFirstByProperty(arr、prop、value){
对于(变量i=0;i
这应该有更好的性能(特别是对于大数组)。平均而言(假设数组中有这样一个元素),它的速度应该是filter和grep的两倍(因为它在第一次匹配时停止).在进行否决表决之前,有人敢发表评论吗?那么问题是什么?以前有人问过这个问题……你不能对对象数组进行直接索引。你必须比较数组中的每个元素。问题仍然没有答案?你应该实际使用jQuery的$.grep
方法(如@DhruvPathak所述)对于这个问题,而不是$().filter
,因为第二个是针对DOM集合的。我对grep的记忆有误。我认为它会在第一次找到元素时停止。因此,对于这个问题,两种解决方案似乎都有不完美的性能。也许应该在这里为性能搜寻者编写一个自己的函数。这将是协调的。
//for defined, non-null values
function findFirstByProperty(arr, prop, value){
for(var i = 0 ; i < arr.length; i++){
if(arr[i]!=null && "undefined" !== typeof arr[i] && arr[i][prop] == value)
return arr[i];
}
return null;
}