(Angular 5) - 为什么 typescript 的 for 只取最后一个数字

(Angular 5) - Why the for of typescript only takes the last number

我正在使用 angular 5,我的组件中有两个数组:

数据数组

data = [{...},{...}]

数组

inputData = [{1,2,3},{4,5,6}]

所以这个问题是因为我想用 inputData.

中的值更改 data 数组中的一些值

为此,我使用这样的迭代器:

for (let x in this.data) {
  this.result = this.data[x].ranges;

  for (let y in this.result) {

    for (let z of this.inputData) {
      this.data[x].ranges[y].ph = z;
    }
  }
}

问题是因为 for 迭代器进行了所有操作来更改该值,但是当我输入 console.log(data) 时,数据数组只有输入数据的最后一个值 (3):

    [ 
      { "name": "Low", "ph": 3, "day": 0 },  <- Check the ph value
      { "name": "Medium", "ph": 3, "day": 0 }, <- Check the ph value
      { "name": "High", "ph": 3, "day": 0 }  <- Check the ph value
    ]

我创建了一个 stackblitz 来展示执行中的问题 (Link to stackblitz)

in 更改为 of

'of' 遍历对象,例如数组。

'in' 遍历对象属性。

这里有两个例子:

另外,我看了你的stackblitz ...逻辑不太对。试试这个:

  constructor() {
    for (let x of this.data) {
      this.result = x.ranges;

      for (let y in this.result) {
          this.result[y].ph = this.inputValues[y];
      }
    }
  }

这是你的 stackblitz 的分支:https://stackblitz.com/edit/angular-ckdrqe?file=src/app/app.component.ts

您的原代码:

for (let x in this.data) {
  this.result = this.data[x].ranges;

  for (let y in this.result) {

    for (let z of this.inputValues) {
      this.data[x].ranges[y].ph = z;
    }
  }
}

第一个循环是按索引循环数据。如我上面的代码副本所示,这通过价值更容易完成。

第二个循环通过索引遍历所有结果...然后对于每个结果它更新 .ph multiple 次因为在那个循环中你正在遍历所有 inputValues。这就是为什么它总是产生最后一个值。

forin 和 javascript/typescript 中的 for 有区别。 forin 与 C# 中的 foreach 或 PHP.

不同
let myObject = {a: 1, b: 2, c: 3};
for(let keys in myObject) {
  // goes through all the keys of an object (i.e. a,b,c)
}

let myArray = [1,2,3];
for(let i = 0; i < myArray.length; i++) {
  // goes through the indexes of an enumerable array (i.e. 0,1,2)
}
// Alternatively, you could also use 
myArray.forEach((value, index, array) => {
   // lists all the values  
}

看来您还没有完全理解 forin。去检查文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

https://www.w3schools.com/js/js_loop_for.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach