gpt4 book ai didi

javascript for 循环遍历带有对象的数组 - 奇怪的结果

转载 作者:行者123 更新时间:2023-11-30 18:39:17 25 4
gpt4 key购买 nike

我有一个数组,我们称它为 foo。数组的每个元素都包含一个对象。

例子:

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 循环对象数组并按原样访问它们?我应该能够从 for 循环中说 foo[x].name(或 foo[x]['name'])来获取值,但我'我变得不确定!有人知道为什么吗?

更新:

因为这个例子是简化的方式,这里是我正在做的完整代码,基本上 pkgs 在运行时填充了 [0]。添加一个新元素(这是一个 add 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/JyLD4/1/

您确定这是问题所在吗?

关于javascript for 循环遍历带有对象的数组 - 奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7326766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com