0

所以我有一个数组,其中填充了对象。这些对象有两个值,一个包含一个列表项,另一个包含一个浮点数(价格)。我正在尝试将列表推送到 DOM 元素中,但该变量是全局未定义的。

此代码将第二个数组项输出到控制台:

$('#coll-price-filter').change(function() {
    var newList = [];
    $('#coll-product-list li').each(function(idx, li) {
        pprice = $(li).find('.coll-prod-price').html().trim().substring(1)
        pprice = parseInt(pprice);
        newList[idx] = {
            value: $(li).wrap('<div></div>').parent().html(),
            price: pprice
        }
        newList.sort(function(a, b){  
            a = a.price, b = b.price;
            return a > b ? 1 : a < b ? -1 : 0;
        });
    });
    console.log(newList[1].value);
});    


然而这并不

$('#coll-price-filter').change(function() {
    var newList = [];
    $('#coll-product-list li').each(function(idx, li) {
        pprice = $(li).find('.coll-prod-price').html().trim().substring(1)
        pprice = parseInt(pprice);
        newList[idx] = {
            value: $(li).wrap('<div></div>').parent().html(),
            price: pprice
        }
        newList.sort(function(a, b){  
            a = a.price, b = b.price;
            return a > b ? 1 : a < b ? -1 : 0;
        });
    });

    i = newList.length;
    while (i > 0) {
        console.log(newList[i].listItem);
        i--;
    }
});    


因此,while 循环似乎破坏了newList[]对象的可访问性。我已经尝试了几种方法,如果我在.each()迭代器中它就可以工作。但我需要在外面访问它。

4

2 回答 2

3

因为数组索引是0基于的,所以:

    i = newList.length;

应该是这样的:

    i = newList.length - 1;

否则,起始索引超出范围,因此newList[i]将是undefined,并且访问属性undefinedTypeError

更正后,您可能希望访问对象上定义的属性,例如.valueor .price,否则它将记录undefined每次迭代。

于 2012-10-02T18:03:10.823 回答
2

这不应该:

i = newList.length;
while (i > 0) {
    console.log(newList[i].listItem);
    i--;
}

是这个吗?

i = newList.length-1; // start on the last index, not length
while (i > 0) {
    console.log(newList[i].value); // value, like in your top example
    i--;
}
于 2012-10-02T18:02:17.513 回答