Sometimes we need to prevent some properties on a JavaScript object from being iterated over and accessed in "for ... in" loops.
In this lesson, we will learn how to use Object.defineProperty()
to hide existing properties on an object by setting the property descriptor flag enumerable
to false
.
const picard = { name: "Jean-Luc Picard", species: "Human", rank: "Admiral", serialNumber: "SP-937-215" }; for (const key in picard) { console.log(picard[key]); } /* Jean-Luc Picard Human Admiral SP-937-215 */
To remove ‘serialNumber‘ from the for..in loop, we can do:
const picard = { name: "Jean-Luc Picard", species: "Human", rank: "Admiral", serialNumber: "SP-937-215" }; Object.defineProperty(picard, "serialNumber", { enumerable: false }); for (const key in picard) { console.log(picard[key]); }
This is becasue for..in loop only iterates over enumerable properties of an object.
[Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript
原文:https://www.cnblogs.com/Answer1215/p/12319093.html