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

How to use for in in js

下次还敢
Release: 2024-05-06 12:51:16
Original
331 people have browsed it

for ... in ... in JavaScript is used to iterate over the enumerable properties of an object, it iterates over the keys (property names) instead of the values. Steps: Declare a variable key to store the current key. Specify the object to be traversed after the in keyword. The loop will traverse each enumerable property of the object and execute the code within the curly braces on each key.

How to use for in in js

How to use for ... in JavaScript

for ... in is a loop statement , used to iterate over the enumerable properties of an object. It iterates over the keys (property names) of the object, not the values.

Syntax

<code>for (let key in object) {
  // 对每个键执行代码
}</code>
Copy after login

Steps

  1. Declare a variable:Declare a variablekey, used to store the current key.
  2. Specify the object: Specify the object to be traversed after the in keyword.
  3. Loop: The loop will continue to iterate through each enumerable property of the object.
  4. Execution code: For each key, the code within the curly brackets will be executed.

Example

<code>const person = {
  name: "John Doe",
  age: 30,
  city: "New York"
};

for (let key in person) {
  console.log(key); // 输出:name, age, city
}</code>
Copy after login

Notes

  • for ... in The loop traverses the keys of the object, not the value.
  • It will traverse enumerable properties. Non-enumerable properties (such as Symbol values) are skipped.
  • The loop sequence is undefined. It may not traverse the properties in the order they were added.
  • For arrays, the for ... in loop will iterate over the array's indices, not the element values.
  • For inherited properties, the for ... in loop will iterate over the properties from the parent object.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template