javascript - 更改两个数组总是同时更改另一个数组

标签 javascript arrays node.js

对于一个项目,我需要导入 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/

相关文章:

javascript - 如何检查数组对象在 for 循环中是否完成

javascript - 如何从对象中检索数据并将其存储到数组中

javascript - 分割 '{a}{b}{c}'?

php - 自定义排序数组

javascript - 我如何在 Express 和 Node.js 中使用 slug?

javascript - Phonegap iOS 应用程序不允许在 iframe 中的表单上进行输入

javascript - 如何在按钮内具有 ng-if 双向条件?

javascript - 打印输出取决于窗口大小

node.js - PencilBlue 在注册表单中添加新字段

javascript - 如何使用 Semantic UI 和 JQuery 在特定卡片上进行调光,而不是在我的所有卡片库上进行切换