Home > Article > Web Front-end > How to use for in in js
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.
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:
Usage:
<code>const person = { name: "John", age: 30 }; for (let key in person) { console.log(key); // 输出:"name", "age" }</code>
<code>for (let key in person) { console.log(person[key]); // 输出:"John", "30" }</code>
<code>for (let key in person) { person[key] = "Updated"; } // person 对象的属性值现在都被更新为 "Updated"</code>
Notes:
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!