JS Split()检查Array中是否存在子字符串

时间:2014-06-10 08:27:00

标签: javascript jquery arrays split

我有array个产品以[{1}}格式存储为Strings格式productname:quantity。我遇到的问题是,如果用户添加一个数量为x的产品,它将被插入到array中。但是,如果他们决定添加更多特定产品,则会在array中添加新条目,而不是检查产品是否已存在并将数量调整为新值。 oldQty + newQty

例如,这是我的数组:

["CBL202659/A:1","OUTER9:1","PALLET CARDS:1"]

如果我添加另一个PALLET CARDS产品,它会创建一个新条目,而不是将现有项目的数量更新为2.

新数组

["CBL202659/A:1","OUTER9:1","PALLET CARDS:1","PALLET CARDS:1"]

我希望数组最终结果如下: - 更新数量

["CBL202659/A:1","OUTER9:1","PALLET CARDS:2"]

目前这是我的代码:

我使用split()方法分隔发生冒号的字符串,并将产品名称和数量存储在两个单独的变量中。

$(".orderBtn").click(function(event){

        //Show the order Box
        $(".order-alert").show();
        event.preventDefault();

        //Create the Array
        var productArray = [];  

        //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();
        var item = stockCode + ":" + quantity;
        var itemCheck = stockCode + ":";

        if(quantity == 0){
            console.log("Quantity must be greater than 0")
        }else{
            //If no Cookie exists, create one and add the Array
            if ($.cookie('order_cookie') === undefined) {
                console.log("CREATE NEW COOKIE");
                //Add items to Array
                productArray.push(item);
                //Add Array to Cookie
                $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });

            //If the Cookie already exists do this  
            } else {
                productArray = JSON.parse($.cookie('order_cookie'));//get ref to array

                if(productArray.indexOf(itemCheck)!= -1){//It exists so update qty
                console.log("EXISTS... updating item: " + itemCheck);
                            //var index = productArray.indexOf(item);
                            //var update = productArray[index].split(":");
                            //var name = update[0];
                            //var oldQty = update[1];
                            //console.log(name + ":" + oldQty);
                            //productArray[index] = item;
                }else{//It does not exist, so add to array
                console.log("Does not exist... adding new item: " + item);
                 //Append items onto the Array
                 productArray.push(item);
                }

                //Update the Cookie
                $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
                console.log($.cookie('order_cookie'));
            }

            //Display the number of items in the Array in the Order Box
            $('#order_counter').html(productArray.length);
        }
    });

我想我在这里提出的真正问题是,是否可以在array中搜索subString - 包含productname: ??

在接受了一些答案和建议后,我稍微修改了我构建array的方式。

但是我遇到了有关名称值对的问题。

步骤1:获取对stockCode和Quantity

的引用
            //Create the Array
        var productArray = [];
        //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();

在控制台中打印它们以确保它们是正确的

PALLET CARDS
2 

第2步:将它们插入数组

    productArray.push({stockCode:quantity});

打印它们以确保它们是正确的 - 不 - 这里有问题......

[Object]
0: Object
stockCode: "2"    <---------------------- Should be PALLET CARDS: "2"
__proto__: Object
length: 1
__proto__: Array[0]

2 个答案:

答案 0 :(得分:0)

尝试:

var input  = ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1","PALLET CARDS:1"],
    dict   = {},
    output = [];

for (var i = 0; i < input.length; i++) {
  var parts = input[i].split(':');
  if (dict[parts[0]] == undefined) {
    dict[parts[0]] = 0;
  }

  dict[parts[0]] += +parts[1];
}

for (var key in dict) {
  output.push([key, dict[key]].join(':'));
}

输出:

["CBL202659/A:1", "OUTER9:1", "PALLET CARDS:2"]

但是,正如Niet the Dark Absol提到的那样,您最终会得到dict对象,如下所示:

Object {CBL202659/A: 1, OUTER9: 1, PALLET CARDS: 2}

并为您提供更多工作能力。

答案 1 :(得分:0)

而不是:

  var item = stockCode + ":" + quantity;
  var itemCheck = stockCode + ":";
  ...

这样做:

编辑:还要检查库存是否存在我认为这样可行......

function checkCode() {
    for (var i=0; i<productArray.length;i++) {
         if (p[i].stockcode==stockCode) {
            p[i].amount+= parseInt(quantity) 
        }
    }

}

if (!checkCode()) productArray.push({ stockcode: stockCode, amount:parseInt(quantity)});

如果您决定使用原始字符串数组...这可能对您有用:

var pArray = ["CBL202659/A:1","OUTER9:1","PALLET CARDS:1"];


for (var i =0; i<pArray.length;i++) {
    var code =  pArray[i].split(":")[0];
    var amount = parseInt(pArray[i].split(":")[1]);

    if (code==stockCode) {
        // code already exists
        amount += parseInt(quantity);
        pArray[i] = code+":"+amount;
    } 
}

然后在上面的例子中使用它..