Home  >  Article  >  Web Front-end  >  How to use for in in js

How to use for in in js

下次还敢
下次还敢Original
2024-05-06 13:03:16577browse

The for...in statement is used to traverse the enumeration properties of the object. Usage: 1. Traverse attribute names: for (key in object). 2. Get the attribute value: for (key in object) {console.log(object[key])}. 3. Set the attribute value: for (key in object) {object[key] = "Updated"}. Note: Only enumerable properties are traversed, the order is undefined.

How to use for in in js

Usage of for...in in JavaScript

for...in is a statement in JavaScript , used to iterate over the enumerable properties of an object. It returns an array of property names that can be used to get or set the property's value.

Syntax:

<code>for (key in object) {
  // 操作
}</code>

Variables:

  • key: Attribute name.
  • object: The object to be traversed.

Usage:

  1. Traverse object properties:
<code>const person = { name: "John", age: 30 };
for (let key in person) {
  console.log(key); // 输出:"name", "age"
}</code>
  1. Get attribute value:
<code>for (let key in person) {
  console.log(person[key]); // 输出:"John", "30"
}</code>
  1. Set attribute value:
<code>for (let key in person) {
  person[key] = "Updated";
}
// person 对象的属性值现在都被更新为 "Updated"</code>

Notes:

  • for...in traverses the enumerable properties of the object. Non-enumerable properties (such as those on the prototype chain) are not traversed.
  • for...in may traverse properties in an undetermined order. Therefore, if you need to traverse in a specific order, you can use the Object.keys() or Object.getOwnPropertyNames() method.

Example:

<code>const array = [1, 2, 3];
for (let key in array) {
  console.log(key); // 输出:0, 1, 2
}
// 注意:数组的属性名是它的索引,而不是实际的数字值。</code>

The above is the detailed content of How to use for in in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does for mean in jsNext article:What does for mean in js