I have an array, lets call it foo. Each element of the array holds an object.
Example:
var foo = new Array();
var test = new Object();
test.name = "Item name1";
test.price = 20.00;
foo.push(test);
var test = new Object();
test.name = "Item name2";
test.price = 10.00;
foo.push(test);
I should now have:
foo[0] => object{name: Item name1, price: 20.00}
foo[1] => object{name: Item name2, price: 10.00}
the problem:
console.log(foo.length); // 2
for(var x = 0; x < foo.length; x++) {
console.log(foo[x]); // foo[x] is undefined 2X
}
Why is it that I cannot for loop the array of objects and access them as such? I should be able to say foo[x].name (or foo[x]['name']) from within the for loop to get the values but I'm getting undefined! any one know why?
Update:
Since that example is way to simplified, here is the full code of what I'm doing, essentially pkgs has [0] populated at the point of running. A new element (this is an add pacakge function) is added then then values are updated. After that I need to use the new insurance values from the two packages to update the UI with the proper insurance values per-package. The very last comment is the interesting part.
var pk = $('#shipment_'+shipid).data('pkgs');
var pkgs = new Array();
for(index in pk) {
pkgs.push(jQuery.extend(true, {}, pk[index]));
}
var pkgnum = pkgs.length; // always returns one higher than last index.
// add new pkg to array
pkgs[pkgnum] = new Object();
pkgs[pkgnum].weight = weight;
// overwrite packing slip data.
for(var x = 0; x < pkgs.length; x++) {
var curPS = new Array();
var curins = 0;
for(var y = 0; y < shipmentItems.length; y++) {
var curqty = parseInt($('#pkgqty-'+y+'-'+x).val());
var nsrow = jQuery.extend(true, {}, shipmentItems[y]);
curins += curqty * shipmentItems[y]['price'];
curPS.push(nsrow);
curPS[y]['qty'] = curqty;
}
pkgs[x].packing_slip = curPS;
pkgs[x].insurance = Math.ceil(curins);
}
// write pkgs data()
$('#shipment_'+shipid).removeData('pkgs');
$('#shipment_'+shipid).data('pkgs', pkgs);
// update insurance values
console.log(pkgs); // shows two objects
console.log("len: " + pkgs.length); // len is 2
for(var x = 0; x <= pkgs.length; x++) {
var insuranceHTML = "$"+pkgs[x].insurance+'<a href="javascript:overrideInsurance('+shipid+','+x+');"><img src="/img/edit2.png" height="16" width="16" alt="" title="Override Insurance Value" align="absmiddle" /></a>';
$('#pkgins-'+shipid+'-'+x).html(insuranceHTML);
// pkgs[x] == undefined when x = 1 but not when x=0
}