将数组对象推入localstorage

时间:2015-07-11 02:59:11

标签: javascript jquery arrays local-storage

 public static void main(String[] args)
{
    String s = "My favorite pet 43 is 12 cat 32 ";
    String split[] = s.split(" ");
    int sum=0;
    for(String str:split){
        try{
            int temp=Integer.parseInt(str);
            sum+=temp;
        }catch(Exception e){
            //
            continue;
        }
    }
    System.out.println(sum);
}

上面代码的问题是在执行它时会替换现有的数组对象,如果order_id不相同,如何将新的obj添加到数组中?

1 个答案:

答案 0 :(得分:-1)

新答案:

var arr = [];
var obj = {};

obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;

$change = 'no'; for(i=0; i<arr.length; i++){ if(obj.order_id == arr[i].order_id){ obj.qty = obj.qty + arr[i].qty; arr[i] = obj; $change ='yes'; } }
if($change == 'no'){ arr.push(obj); }

console.log(arr);

要将其保存在localstorage中,请在此处查看我的答案:push multiple array object into localhost?

旧答案: 最好的解决方案是制作&#39; arr&#39; order_id是对象键的对象。你得到这样的东西:

var arr = {};
var obj = {};

obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;

arr[obj.order_id]= obj;
console.log(arr);

如果order_id相同,这只会替换订单。如果你真的想要和数组,你必须创建一个遍历数组并检查每个order_id的函数。