我创建了这个对象,以便您可以仅使用对象而无需将其设置为数组。
let info = {
0: { ProId: "Space", Name: "cake", Quantity: "1" },
1: { ProId: "new", Name: "walk", Quantity: "2" },
2: { ProId: "foo", Name: "bar", Quantity: "3" }
}
function incrementQuantify(obj) {
let _newInfo = {};
for (const key of Object.keys(obj)) {
info[key].Quantity = parseInt(info[key].Quantity, 10) + 1;
_newInfo[key] = info[key];
}
return _newInfo;
}
console.log(incrementQuantify(info));
较短的方式:
let info = { 0: { ProId: "Space", Name: "cake", Quantity: "1" }, 1: { ProId: "new", Name: "walk", Quantity: "2" }, 2: { ProId: "foo", Name: "bar", Quantity: "3" } }
for (const key of Object.keys(info)) info[key].Quantity = parseInt(info[key].Quantity, 10) + 1;
console.log(info);
编辑:我已经找到一种处理数组的方法!
let info = [
{ ProId: "Space", Name: "cake", Quantity: "1" },
{ ProId: "new", Name: "walk", Quantity: "2" },
{ ProId: "foo", Name: "bar", Quantity: "3" }
]
function incrementQuantify(obj) {
let newObj = obj;
newObj.Quantity = parseInt(obj.Quantity, 10) + 1;
return newObj;
}
info.map(incrementQuantify);
console.log(info);
更短的方式:
let info = [ { ProId: "Space", Name: "cake", Quantity: "1" }, { ProId: "new", Name: "walk", Quantity: "2" }, { ProId: "foo", Name: "bar", Quantity: "3" } ]; info.map(o => o.Quantity = parseInt(o.Quantity, 10) + 1);
console.log(info);
希望能有所帮助!
console.log(Array.isArray(info))
的结果是什么? - vidu.shinfo
确实是一个数组。你可以查看下面的解决方案,建议使用 Array.forEach 或 Array.map 进行循环。 - vidu.sh