对于一个项目,我需要导入 Excel 文件,将数据更改为 JSON,并以不同的方式重新格式化它,以便我的应用程序可读。其中一个步骤是将 Excel 的一行拆分为两个不同的数组,这两个数组必须单独更改。
但是无论我做错了什么 - 对其中一个数组的任何更改不仅会相应地更改另一个数组,还会相应地更改我的原始数据。
let data = [{
value1: 1,
value2: 2
}, {
value1: 3,
value2: 4
}]
let temp1 = [];
let temp2 = [];
for (let x of data) {
temp1.push(x); //pushing x in array 1
temp2.push(x); //pushing x as well in array 2
}
for (let x of temp1) {
x.type = 'typeA'
}
for (let x of temp2) {
x.type = 'typeB'
}
console.log(JSON.stringify(data));
console.log(JSON.stringify(temp1));
console.log(JSON.stringify(temp2));
//all three give the same result.
有人知道我的代码哪里出了问题吗?
最佳答案
Javascript 数组是基于引用的 - 因此您可以将其视为包含对同一值的引用的数组 1 和数组 2。更改一个数组中的值也会更改另一个数组中的值,因为无论如何它们都是相同的底层事物。
您真正需要的是如何深度克隆值。以下是如何克服该限制的示例。
let data = [{
value1: 1,
value2: 2
}, {
value1: 3,
value2: 4
}]
let temp1 = [];
for (let x of data) {
temp1.push(x); //pushing x in array 1
}
// This is one of the "workaround ways" of constructing
// an array of fresh values (otherwise known as deep cloning).
// this doesn't work in cases where you might have cyclic javascript
// objects or functions, but works if you're dealing with JSON values.
let temp2 = JSON.parse(JSON.stringify(temp1));
for (let x of temp1) {
x.type = 'typeA'
}
for (let x of temp2) {
x.type = 'typeB'
}
console.log(JSON.stringify(data));
console.log(JSON.stringify(temp1));
console.log(JSON.stringify(temp2));
//all three give the same result.
因为您实际上知道您的数据是一个对象列表,所以这可以工作。在实践中,您可能想要使用更强大的东西......例如lodash的cloneDeep:https://lodash.com/docs/4.17.4#cloneDeep
关于javascript - 更改两个数组总是同时更改另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198522/