Home > Article > Web Front-end > Differences in using for...in and Object.keys() to enumerate object properties in JavaScript (code attached)
The content of this article is about the difference between using for...in and Object.keys() to enumerate object properties in JavaScript (with code). It has certain reference value. Friends in need can For reference, I hope it will be helpful to you.
You can get the properties of an object using both the for...in loop and the Object.keys method. So what is the difference between them? Suppose there is an object a:
var a = {x: 1, y: 2}; Object.defineProperty(a, 'z', {value: 3}); // 定义不可枚举属性z var keys = []; for (var key in a) { keys.push(key); } console.log(keys); console.log(Object.keys(a));
The output result of the program is:
Both methods obtain all the enumerable attributes of the object, and for Non-enumerable properties cannot be obtained either way.
Below is an object b, and b is used as the prototype object of object a:
var b = {bx: 1, by: 2}; Object.defineProperty(b, 'bz', {value: 3}); Object.setPrototypeOf(a, b);
Use the above method to output the key value of a, and the result is as follows:
It is not difficult to see from the output results that the for...in loop can traverse all enumerable properties of the object, including properties in the prototype object, while only the enumerable properties of the object can be obtained through Object.keys The own properties of the example, so if you want to get the object's own properties through for...in, you can filter the results through the hasOwnProperty method:
var keys = []; for (var key in a) { if (a.hasOwnProperty(key)) { keys.push(key); } }
You can also get the object's own properties through Object.getOwnPropertyNames .
It can be seen from the above output that the result output by the getOwnPropertyNames method also contains the non-enumerable properties of the object. You can use Object.propertyIsEnumerable to determine whether the property is enumerable. To filter the results:
The above is the detailed content of Differences in using for...in and Object.keys() to enumerate object properties in JavaScript (code attached). For more information, please follow other related articles on the PHP Chinese website!