Uncaught TypeError: items is not iterable

Uncaught TypeError: items is not iterable

我的理解是 for...in 循环旨在迭代 Javascript 中的对象。 See this post and this post.

举个例子。这个 returns 'Uncaught TypeError: items is not iterable' 在我的控制台中。

var text = {
  name: "Coptic",
  ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
  direction: "ltr",
  year: -200,
  living: false,
  link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
};

function dominantDirection(items) {
  for (let item of items) {
    if (item.direction === 'ltr') {
      return 'ltr';
    } else {
      return 'rtl';
    }
  }
}

console.log(dominantDirection(text));

如果我将对象包装在数组中[],它就可以正常工作。 但是,我的第二个示例按预期工作。

var object1 = {a: 1, b: 2, c: 3};
var string1 = "";

function loopObj() {
  for (var property1 in object1) {
    console.log(string1 = string1 + object1[property1]);
  }
}

console.log(loopObj());

为什么第一个示例需要数组而第二个示例不需要?

在您的第一个示例中,您使用了 for..of,它不能用于对象,只能用于字符串和数组。要迭代对象,可以使用 for..in 构造,也可以使用 Object.keys().

将对象的键放入数组中

示例使用 Object.keys():

const text = {
  name: "Coptic",
  ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
  direction: "ltr",
  year: -200,
  living: false,
  link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
};

for (let key of Object.keys(text)) {
  
  console.log(`${key}: ${text[key]}`);
}

或者您也可以使用新的 Object.entries() 来获取键和值,如下所示:

const text = {
  name: "Coptic",
  ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
  direction: "ltr",
  year: -200,
  living: false,
  link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
};

for (let [key, value] of Object.entries(text)) {
  
  console.log(`${key}: ${value}`);
}