Javascript - 尝试遍历对象时 for-of 循​​环崩溃

Javascript - for-of loop crashing when trying to loop through an object

我通过函数传入了这个对象

然后我想用这段代码遍历它

    let formData = new FormData();
    let item = {};
    let i = 0;
    for (item of files) {
        formData.append('file' + i, files[i]);
        formData.append('filesNumber', i + 1);
        i++;
    }

但是当执行到for循环的声明时,它崩溃并出现这个错误

Uncaught TypeError: files[Symbol.iterator] is not a function

怎么了?

基本对象不会自动实现 Symbol.iteratorHere's a list of objects that do.

为了使用 for..of 语法,您必须实现自己的迭代器。

let files = {
  0: "a",
  1: "b",
  2: "c",
  
  [Symbol.iterator]: function*() {
    let i = 0;
    while (this.hasOwnProperty(i)) {
      yield this[i];
      i++;
    }
  }
};

for (let item of files) {
  console.log(item);
}

或者,您只需 grabs the objects keys 并迭代它们。

let files = {
  0: "a",
  1: "b",
  2: "c"
};

let keys = Object.keys(files);
for (let i = 0; i < keys.length; i++) {
  let key = keys[i];
  let item = files[key];
  console.log(`${key}: ${item}`);
}

您还可以使用 old-fashioned for..in 循环遍历键。

let files = {
  0: "a",
  1: "b",
  2: "c"
};

for (let key in files) {
  console.log(`${key}: ${files[key]}`);
}