The traversal range of js for...in, the meaning of hasOwnProperty judgment

Most editors have code block function, some editors (such as VS code) provide for...in code block code as follows

for (const key in object) {
    
    
	if (object.hasOwnProperty(key)) {
    
    
		const element = object[key];
		
	}
}

In addition to for (in) (), it also contains an object.hasOwnProperty(key) judgment

When I was young, I wondered why there is such a judgment that the key comes from the object, so it must belong to the object. Isn't this judgment unnecessary?
Therefore, I did not realize the importance of the object.hasOwnProperty(key) judgment.

Until I met such an object

var arr = {
    
    
	a: "lv1",
	__proto__: {
    
    
		b: "lv2",
		__proto__: {
    
    
			c: "lv3",
			__proto__: {
    
    
				c: "lv4",
			}
		}
	}
}

for(const key in arr) {
    
    
	console.log(key, arr[key])
};

// a lv1
// b lv2
// c lv3

In addition to the first layer a lv1, it also outputs strange things b lv2, c lv3.
Obviously, this is not the result I expected!

Fortunately, my prototype chain has a bit of foundation. I know that the strange things come from the depths of the prototype chain __proto__, and then I checked it on the Internet and found out the cause of the problem.

The traversal scope of for...in includes its prototype chain

Moreover, as long as the attribute names do not conflict, the deeper attributes of the prototype chain can be found.

Now that the crux of the problem is known, it is easy to solve the problem.



hasOwnProperty

The hasOwnProperty() method returns a boolean value indicating whether the object’s own properties have the specified property (that is, whether there is a specified key).
Simply put, hasOwnProperty is used to determine that the property is the object’s own, rather than inherited or someone else’s

The original if(object.hasOwnProperty(key)) {} in for…in does not come from the outside world, but the object’s own prototype

There is no doubt that after adding the object.hasOwnProperty(key) judgment, the result is in line with the expected effect

var arr = {
    
    
	a: "lv1",
	__proto__: {
    
    
		b: "lv2",
		__proto__: {
    
    
			c: "lv3",
			__proto__: {
    
    
				c: "lv4",
			}
		}
	}
}

for(const key in arr) {
    
    
	if(arr.hasOwnProperty(key)) {
    
    
		console.log(key, arr[key])
	}
};

// a lv1

//end

Guess you like

Origin blog.csdn.net/u013970232/article/details/109530938