添加对象到JS数组

Adding Objects to JS Array

本文关键字:数组 JS 对象 添加      更新时间:2023-09-26

我正在尝试创建包含与订单相关的两条信息的objectsarray:

  1. 产品库存代码
  2. 产品数量

目前我是这样做的:

$(".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 key = "stockCode";
        var obj = {
            'stockCode' : stockCode,
            'quantity'  : quantity
        };
        productArray.push(obj);
        $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
        console.log(productArray);
        if(quantity == 0){
            console.log("Quantity must be greater than 0")
        }

我希望每次单击订单按钮时,新对象将被添加到现有对象的array中,但它只输出带有1个对象的array,即我刚刚添加的对象。

我错过了什么吗?

将函数外的数组声明移到全局作用域中。
在这种情况下,每次调用函数时都会创建一个新的数组(函数作用域),因此只产生一个结果。

阅读这篇关于作用域'提升的文章。

var productArray = [];
$(".orderBtn").click(function(event){
        //Show the order Box
        $(".order-alert").show();
        event.preventDefault();
        //Create the Array
        //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 key = "stockCode";
        var obj = {
            'stockCode' : stockCode,
            'quantity'  : quantity
        };
        productArray.push(obj);
        $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
        console.log(productArray);
        if(quantity == 0){
            console.log("Quantity must be greater than 0")
        }

声明为全局变量

 var productArray = [];
    $(".orderBtn").click(function(event){
    // do here 
    //productArray.push("anyObject"); 
    });

每次单击按钮时都要重新创建/覆盖productArray。尝试将var productArray = []移动到点击处理程序

的外部

不是这样的,因为你的

var productArray = [];

在设置cookie的函数中,因此它被重新定义,然后每次调用该函数时添加一个元素。

您需要在函数外部定义productArray(作为一个全局变量?),以便它保留其先前的值,并向其添加新对象

使用var productArray = [];,您将在每次单击时声明一个新数组。将这行移到click处理程序之外,代码应该开始工作了。