我试图改变" formDataArray"中数组的值。但是,当我做出任何改变时,它会保留但重写整个对象。这可能是一个不变的问题,我尝试过研究,但我已经放弃了。如何在" formDataArray"中更改数组的值?持久地;
if ((value, pos, name)) {
var formDataArray = {
code: [],
desc: [],
qty: [],
prices: [],
line_price: []
};
switch (name) {
case "description":
formDataArray.desc[pos - 1] = value;
break;
case "code":
formDataArray.code[pos - 1] = value;
break;
case "qty":
formDataArray.qty[pos - 1] = value;
break;
case "price":
formDataArray.prices[pos - 1] = value;
break;
case "line_price":
formDataArray.line_price[pos - 1] = value;
break;
default:
}
console.log(formDataArray);
}
答案 0 :(得分:1)
我不确定这是否是您正在寻找的内容:我理解您要构建一个update()
函数,以便更新对象中包含的内容{{1} }。
在这种情况下,定义一个新函数,不需要if语句。该函数将作为参数提供有关修改的必要信息,并在现有数组(而非新数组)中进行更改。
以下是一个示例代码:
formDataArray

我在var formDataArray = {
code: [193, 843, 393],
desc: ['pen', 'table', 'cards'],
qty: [1, 2, 3],
prices: [5, 50, 10],
line_price: [3, 2, 1]
};
let update = function(value, pos, name) {
switch (name) {
case "description":
formDataArray.desc[pos - 1] = value;
break;
case "code":
formDataArray.code[pos - 1] = value;
break;
case "qty":
formDataArray.qty[pos - 1] = value;
break;
case "price":
formDataArray.prices[pos - 1] = value;
break;
case "line_price":
formDataArray.line_price[pos - 1] = value;
break;
default:
}
return formDataArray;
}
console.log(formDataArray)
update(12, 2, 'price')
console.log(formDataArray)
中添加了一些示例数据。观察控制台,看看价格数组的变化。
答案 1 :(得分:0)
每次编辑Object时都会初始化formDataArray。在if语句上方定义对象方式,使其成为代码中的第一行:
var formDataArray = {
code: [],
desc: [],
qty: [],
prices: [],
line_price: []
};
if ((value, pos, name)) {
switch (name) {
case "description":
formDataArray.desc[pos - 1] = value;
break;
case "code":
formDataArray.code[pos - 1] = value;
break;
case "qty":
formDataArray.qty[pos - 1] = value;
break;
case "price":
formDataArray.prices[pos - 1] = value;
break;
case "line_price":
formDataArray.line_price[pos - 1] = value;
break;
default:
}
console.log(formDataArray);
}