简体   繁体   English

无法在 object 上使用 for of 循环遍历我的 object

[英]Not able to iterate through my object using for of loop over an object

I'm trying to iterate through an object but getting an error我正在尝试遍历 object 但出现错误

 const myObj = { number1: 4, number2: 10 } for (const key of myObj) { console.log(`${key}: ${myObj[key]}`); }

but instead getting a console error而是得到一个控制台错误

You are actually making a very minor mistake.你实际上犯了一个非常小的错误。 You are creating an object and using for.. of for that but for..of is use to iterate over an array.您正在创建一个 object 并使用for.. of ,但for..of用于迭代数组。 Use for..in instead which iterates over an object keys.使用for..in代替它迭代 object 键。

Here's your working demo:这是您的工作演示:

const myObj = {
  number1: 4,
  number2: 10
}
    for (const key in myObj) {
  console.log(`${key}: ${myObj[key]}`);
}

Use for..in instead of for..of .使用for..in代替for..of

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbol s), including inherited enumerable properties. for...in语句遍历 object 的所有可枚举属性,这些属性以字符串为键(忽略以Symbol为键的),包括继承的可枚举属性。

The for...of statement creates a loop iterating over iterable objects , including: built-in String ,Array , array-like objects (eg, arguments or NodeList ), TypedArray , Map , Set , and user-defined iterables. for...of语句创建一个循环迭代可迭代对象,包括:内置StringArray 、类数组对象(例如argumentsNodeList )、 TypedArrayMapSet和用户定义的可迭代对象。 It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.它调用一个自定义迭代钩子,其中包含要为 object 的每个不同属性的值执行的语句。

Try below.下面试试。

 const myObj = { number1: 4, number2: 10 } for (const key in myObj) { console.log(`${key}: ${myObj[key]}`); }

Replace of with in in替换

for...of is used in String, Array, array-like objects. for...of用于字符串、数组、类数组对象。

Whereas in is an operator that returns true if the specified property is in the specified object .in是一个运算符,如果指定的属性在specified object中,则返回true

 const myObj = { number1: 4, number2: 10 } for (const key in myObj) { console.log(`${key}: ${myObj[key]}`); }

Your Error is using for... of instead of for... in in your loop.您的错误是在循环中使用for... of而不是for... in To iterate through object I think that using Object methods is better to process your data:要遍历 object 我认为使用 Object 方法更好地处理您的数据:

Object.entries(myObj2).forEach(([key, value]) => console.log(key, value))

You can also use keys method that gives you only the key and values that gives you only the values.您还可以使用只为您提供键和值的键方法,该方法只为您提供值。

Here's good variant, this works perfect:这是一个很好的变体,这很完美:

const myObj = {
  number1: 4,
  number2: 10,
};

Object.keys(myObj).forEach((key) => {
  console.log(`${key}: ${myObj[key]}`);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM