我有一个数组,它似乎在1次迭代后出错。我正在查询数据库(订单(并返回值。如果查询只返回了一组数据,那么它是有效的,但如果有多个数据,我会在myOrders[1]上出错。我认识到这与我只声明数组中的一行有关,但我不知道数组需要有多大(因为查询可能是1或多个(,那么在I=1的迭代中,避免出错的正确方法是什么?
var myOrders = [
{ "Date": " ", "Order": " ", "Units": " ", "Cost": " " },
];
var o = orders.orders;
var oq = o.length;
for (var i = 0; i < oq; i++) {
myOrders[i].Date = o[i].pickupDate;
myOrders[i].Order = o[i].laundry;
myOrders[i].Units = o[i].quantity;
myOrders[i].Cost = o[i].amount;
};
感谢您提供的任何帮助!
执行此操作。在这里,myOrders将根据o.动态创建
var myOrders = [];
var o = orders.orders;
var oq = o.length;
for (var i = 0; i < oq; i++) {
const someObject = {};
someObject.Date = o[i].pickupDate;
someObject.Order = o[i].laundry;
someObject.Units = o[i].quantity;
someObject.Cost = o[i].amount;
myOrders.push(someObject)
};
您在myOrder中只有一个元素,第二次迭代时myOrders[i]
将未定义,因此myOrder[i].someProperty
将抛出错误。
你可以简单地使用映射函数,并将值映射到新的密钥
let myOrders = o.map(({pickupDate, laundry, quantity, amount})=> ({Date, Order, Units, Cost}))