How to use for in in js

下次还敢
Release: 2024-05-06 12:51:16
Original
226 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 ... inis 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

for (let key in object) { // 对每个键执行代码 }
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 theinkeyword.
  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

const person = { name: "John Doe", age: 30, city: "New York" }; for (let key in person) { console.log(key); // 输出:name, age, city }
Copy after login

Notes

  • for ... inThe loop traverses thekeysof the object, not the value.
  • It will traverseenumerableproperties. Non-enumerable properties (such as Symbol values) are skipped.
  • The loop sequence isundefined. It may not traverse the properties in the order they were added.
  • For arrays, thefor ... inloop will iterate over the array's indices, not the element values.
  • For inherited properties, thefor ... inloop 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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!