如何使用for...in遍历实例化对象以替代forEach方法?
Absolutely! You can totally use for...in to loop through the key-value pairs of your Person instances. Let me show you how to adjust your code to do that, including a best practice to avoid picking up unexpected inherited properties.
First, I’ll assume your persons variable is an array holding your three instances, like this:
var persons = [person01, person02, person03];
Iterating over each person’s properties with for...in
For each Person object, for...in will go through all its enumerable properties. To ensure you only get the properties directly defined on the instance (and not ones inherited from the Person prototype or the base Object), use the hasOwnProperty() method. Here’s how:
// Loop through each person in the array (standard for loop is ideal for arrays) for (let i = 0; i < persons.length; i++) { const currentPerson = persons[i]; console.log(`--- ${currentPerson.fullName}'s Details ---`); // Use for...in to iterate over the current person's key-value pairs for (const key in currentPerson) { // Check if the property belongs directly to the instance if (currentPerson.hasOwnProperty(key)) { console.log(`${key}: ${currentPerson[key]}`); } } }
If you want to use for...in for the array too (note: not recommended for arrays)
While for...in works on arrays, it’s generally not the best choice because it can iterate over non-index properties (like if you added custom methods to the array prototype). But if you still want to use it, here’s how:
for (const index in persons) { // Make sure we're only dealing with valid array indices if (persons.hasOwnProperty(index)) { const currentPerson = persons[index]; console.log(`--- ${currentPerson.fullName}'s Details ---`); for (const key in currentPerson) { if (currentPerson.hasOwnProperty(key)) { console.log(`${key}: ${currentPerson[key]}`); } } } }
Quick Tips:
for...inloops over enumerable properties, which includes both instance-specific properties and any inherited enumerable ones. That’s whyhasOwnProperty()is so useful—it filters out the inherited stuff you don’t need.- If you’re certain there are no inherited properties you need to worry about, you could skip the
hasOwnProperty()check, but it’s a safe habit to keep to avoid unexpected bugs down the line.
Hope this matches what you were doing with forEach!
内容的提问来源于stack exchange,提问作者jaumeserr

