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
0based, this:should be this:
Otherwise the starting index is out of bounds, so
newList[i]will beundefined, and accessing a property onundefinedis a TypeError.Once you correct that, you probably want to access a property defined on the object, like
.valueor.price, otherwise it will logundefinedfor each iteration.