添加对象到JS数组
Adding Objects to JS Array
我正在尝试创建包含与订单相关的两条信息的objects
的array
:
- 产品库存代码
- 产品数量
目前我是这样做的:
$(".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处理程序之外,代码应该开始工作了。
相关文章:
- 在数组JS中查找三个重复项
- 比较二维数组js
- 从数组(JS)中的对象调用函数
- 检查对象是否已被推入数组 Js
- 将CSV文件转换为JSON数组JS
- 解析多维数组JS的数组并记录索引
- 如何遍历直接传递到灰尘的数组.js
- 如何使用 D3 选择 JSON 数组.js 使用 .算子
- JavaScript 变量中的 PHP 数组 - JS 元素
- 将数据复制到 JavaScript D3 中的数组.js然后绘制散点图
- 基于数组JS中的值创建按钮
- 创建数组JS
- 按频率排序子字符串数组-JS
- 将数组js变量传递给php
- 使用不带嵌套循环的数组过滤对象数组js
- 创建封装数组JS
- 创建多dim数组(JS)
- 创建for循环对象并将它们压入数组js中
- 将数组JS中的所有项相乘
- 如何从二维数组(JS)中获取网格的坐标