如何向多维关联数组中添加数据

3
我正在遍历页面上的一些HTML表单元素,代码如下。
var itemsArray = new Array();
$('input[type="text"].qty').each(function(index) {
    if($(this).val()) {
        itemsArray[index]['qty'] = $(this).val();
        itemsArray[index]['itemPrice'] = $(this).parents('.control-group').find('.itemPrice').val();
        itemsArray[index]['itemID'] = $(this).parents('.control-group').find('.itemID').val();
    }
});

我希望index可以像普通数组一样是0,1,2,3等。子元素是关联的,并被分配给不同的值。

控制台显示以下错误:

TypeError: itemsArray[index]未定义


1
在Javascript中,没有关联数组。有数组和对象。数组可以包含对象,对象也可以包含数组。在您的情况下,您需要一个对象数组,因此对于每个索引,您将不得不向数组添加一个对象,然后填充该对象。您还可以先创建对象,然后将其添加到数组中,以使其更有意义。 - Kevin B
1
你的代码可以压缩成这个:http://pastebin.com/H0AP8Y20 - Kevin B
3个回答

7

在开始使用外部数组中的每个项目之前,您需要确保对其进行初始化。请注意,下面我仅出于清晰起见更改为对象表示法。

$('input[type="text"].qty').each(function(index) {
    if($(this).val()) {
        itemsArray[index] = {};
        itemsArray[index].qty = $(this).val();
        itemsArray[index].itemPrice = $(this).parents('.control-group').find('.itemPrice').val();
        itemsArray[index].itemID = $(this).parents('.control-group').find('.itemID').val();
    }
});

这就是为什么人们在处理完 PHP 数组后,会在处理 JavaScript 数组时感到困难的主要原因。 - Jeff Noel
@Ghillied - 是的,绝对没问题。 - Justin Bicknell

4
考虑使用对象数组。在Javascript中,数组并不是真正意义上的多维数组。同时,itemsArray = []new Array()更受推荐。
var itemsArray = [];
$('input[type="text"].qty').each(function(index) {
    if($(this).val()) {
        itemsArray.push({
            qty : $(this).val(),
            itemPrice :  $(this).parents('.control-group').find('.itemPrice').val(),
            itemID : $(this).parents('.control-group').find('.itemID').val()
        });

    }
});

1
这句话的意思是,它说了什么就是什么。itemsArray[index]undefined,你不能对其进行属性赋值。请注意,你没有一个“多维数组”,而只是一个对象数组。对于每个新的index,你需要创建一个新的对象。
var $this = $(this);
if ($this.val()) {
    var $parent = $(this).parents('.control-group'); // .closest() should suffice
    itemsArray[index] = {
        qty: $this.val(),
        itemPrice: $parent.find('.itemPrice').val(),
        itemID: $parent.find('.itemID').val()
    };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接