首页 > 编程语言 > 详细

[Javascript] Hide Properties from Showing Up in "for ... in" Loops in JavaScript

时间:2020-02-16 23:06:48      阅读:51      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!