【问题标题】:Using indexOf( ) to check if particular object exists in JS Array使用 indexOf() 检查特定对象是否存在于 JS 数组中
【发布时间】: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


【解决方案1】:

我希望我没听错:

   function findByStockCode(code, stockCodeArr){
           return stockCodeArr.filter(function(elem){
              return elem.stockCode == code;
           });
   }

这当然会给你一个数组。如果长度大于零,则具有给定代码的元素已经在数组中。我认为过滤器功能已在 ECMA5 中添加,因此 IE8 可能不支持它。
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter][1] 提到了在当前浏览器中未实现过滤器的情况下的后备。
无论如何,有一个类似的 jQuery 函数,其中 'this' 指的是实际元素:

function jQueryFindByStockCode(code, stockCodeArr){
               return $(stockCodeArr).filter(function(){
                  return this.stockCode == code;
               });
       }

编辑:
正如 DhruvPathak 提到的,$.grep 可能是比 jQuery 的过滤器更合适的解决方案。 (Grep vs Filter in jQuery?)

我再次寻找具有更好性能的解决方案(似乎)您可以自己编写(反正很简单):

//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;
}

这应该有更好的性能(尤其是对于大数组)。平均而言(假设数组中有这样一个元素),它的平均速度应该是 filter 和 grep 的 两倍(因为它在第一次匹配时停止)。

【讨论】:

  • 你实际上应该使用 jQuery 的 $.grep 方法(正如 @DhruvPathak 所提到的)而不是 $().filter,因为第二个是用于 DOM 集合。
  • 我记错了 grep。我以为它会在第一次找到元素时停止。因此,对于这个问题,这两种解决方案似乎都有不完美的表现。也许应该在这里为性能猎人编写一个自己的函数。
  • Harmony 中的 find()
【解决方案2】:

使用 jquery grep 来匹配数组中“stockcode”键等于您的 stockCode 的元素

http://api.jquery.com/jquery.grep/

【讨论】:

    【解决方案3】:

    我认为你需要这样使用:

    $.inArray( stockCode, productArray)
    

    更多信息here

    【讨论】:

    • 在投反对票之前有人敢发表评论
    • 那是什么问题?
    猜你喜欢
    • 2020-11-30
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多