📜  js for in object - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:58.611000             🧑  作者: Mango

JS For-In Loop with Objects

When working with objects in JavaScript, the for-in loop is a handy tool for iterating over all the properties within an object.

Here's an example:

let person = {name: "John", age: 30, occupation: "Developer"};
for(let prop in person) {
  console.log(prop + ": " + person[prop]);
}

This will output:

name: John
age: 30
occupation: Developer

The for-in loop goes through each property in the object and assigns the property name to the prop variable. We can then use that variable to access the property value with person[prop].

If we only want to iterate over the object's own properties, and not any properties it might inherit from its prototype:

for(let prop in person) {
  if(person.hasOwnProperty(prop)) {
    console.log(prop + ": " + person[prop]);
  }
}

This will output the same result as before.

One thing to be aware of when using for-in loop is that it iterates over all the enumerable properties of an object, including those that are inherited from its prototype chain. To avoid this, one approach is to use Object.keys() method to get an array of only the object's own enumerable properties:

let ownProps = Object.keys(person);
for(let i = 0; i < ownProps.length; i++) {
  let prop = ownProps[i];
  console.log(prop + ": " + person[prop]);
}

This will output the same result as the previous examples.

In summary, the for-in loop provides a convenient way to iterate over all properties of an object in JavaScript, but it's important to be aware of its limitations and use appropriate precautions to avoid iterating over properties inherited from a prototype chain.