How to use for in in js

下次还敢
Release: 2024-05-06 13:03:16
Original
492 people have browsed it

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:

for (key in object) { // 操作 }
Copy after login

Variables:

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

Usage:

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

Notes:

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

Example:

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

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!