我有一个数组,我们称它为foo。数组的每个元素都包含一个对象。javascript for循环数组与对象 - 奇怪的结果
例子:
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);
我现在应该有:
foo[0] => object{name: Item name1, price: 20.00}
foo[1] => object{name: Item name2, price: 10.00}
问题:
console.log(foo.length); // 2
for(var x = 0; x < foo.length; x++) {
console.log(foo[x]); // foo[x] is undefined 2X
}
为什么我不能为循环对象数组和访问它们因此?我应该可以在for循环中说foo[x].name
(或foo[x]['name']
)来获取值,但我得到的是undefined!任何人都知道为什么?
更新:
自认为的例子是办法简化,这里是我在做什么的全部代码,基本上PKGS已[0]填充在运行的点。添加一个新元素(这是一个添加pacakge函数),然后更新值。之后,我需要使用这两个软件包中的新保险值,以每个软件包的适当保险值更新UI。最后的评论是有趣的部分。
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
}
似乎正常工作对我来说:http://jsfiddle.net/68Msz/14/ –
在这个例子中没有jQuery,jQuery标签有误导性 –
我在这里看不到任何问题。你确定在那里有完全相同的代码吗? –