简体   繁体   中英

Array Object Acceptable Globally, but Not in Loops

So I have an array, which is populated with objects. The objects have two values, one containing a list item, and another containing a float (price). I'm trying to push the list into a DOM element, but the variable is globally undefined.

This code outputs the second array item to the console:

$('#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);
});    


However this does not

$('#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--;
    }
});    


So it appears that the while loop is breaking the accessibility of the newList[] object. I've tried it a few ways, and it works if I'm inside the .each() iterator. But I need to access it outside.

Because Array indices are 0 based, this:

    i = newList.length;

should be this:

    i = newList.length - 1;

Otherwise the starting index is out of bounds, so newList[i] will be undefined , and accessing a property on undefined is a TypeError .

Once you correct that, you probably want to access a property defined on the object, like .value or .price , otherwise it will log undefined for each iteration.

Shouldn't this:

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

Be this?

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--;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM