当前位置:网站首页>转载 :判断对象是否具有属性的5种方法
转载 :判断对象是否具有属性的5种方法
2022-06-29 08:42:00 【逆风优雅】
在编程开发时,我们经常需要判断一个对象是否具有某种属性。在这里,我们列出 了5种判断对象属性的方法。
1、in Operator
如果指定属性在指定对象或其原型链中,则 in Operator 返回 true。
用法:

但是 in Operator有个缺点,那就是:如果属性来自对象的原型,它仍然会返回 true。

2、Reflect.has() 方法
Reflect.has 方法允许我们检查属性是否在对象中。它像 in Operator 一样作为函数工作。
用法:

3、 hasOwnProperty() 方法
hasOwnProperty() 方法返回一个布尔值,指示对象是否具有指定的属性作为它自己的属性(而不是继承它)。
它可以正确地区分对象本身的属性和其原型的属性。
用法:

但是这种写法有个缺点,就是如果对象是用Object.create(null)创建的话,那么就不能用这个方法了。

4、Object.prototype.hasOwnProperty() 方法
解决前面的问题很简单,我们只需要使用Object.prototype.hasOwnProperty。该方法是直接调用内置的有效用函数,跳过原型链。

5、Object.hasOwn() 方法
由于前面的几种方式都不优雅,ES2022有一个新的提议:Object.hasOwn
如果指定的对象具有指定的属性作为其自己的属性,则 Object.hasOwn() 静态方法返回 true。如果属性被继承或不存在,则该方法返回 false。
用法:

边栏推荐
- Easyexcl export 1million lines of EXECL report font error solution
- Research progress of target detection in the era of deep convolutional neural network
- YOLO Nano:一种高度紧凑的只看一次的卷积神经网络用于目标检测
- 长安链数据存储介绍及Mysql存储环境搭建
- Uber 前安全主管面临欺诈指控,曾隐瞒数据泄露事件
- Pytorch summary learning series - operation
- pytorch总结学习系列-操作
- UE4 installs the datasmith plug-in in version 4.20-23
- What is hyperfusion? What is the difference with traditional architecture
- UE4 remove the mask transparent white edge in the material
猜你喜欢

UE4 animation redirection

Wechat applet determines the file format of URL

Easyexcl export 1million lines of EXECL report font error solution

数据可视化:数据可视化四象限,教你正确应用图标

UE4 blueprint modify get a copy in array to reference

Detecting and counting tiny faces

微信小程序项目:tab导航栏

Instance error iopub data rate exceeded

Training kernel switching using GPU

Summary of 3DMAX jamming, white screen and rendering crash
随机推荐
爱快安装或重置后,PC或手机端获取不到ip
Detailed version of two-stage target detection principle
pytorch总结学习系列-广播机制
五心公益红红娘团队
深卷积神经网络时代的目标检测研究进展
GD32F4xx 以太網芯片(enc28j60)驅動移植
pytorch总结—自动求梯度
ISO16000-9建筑产品和家具中挥发性有机物的测试
How to implement observer mode
(transfer) mysql: error 1071 (42000): specified key was too long; max key length is 767 bytes
Wechat applet sharing page, sharing to the circle of friends
LSM6DSL之SPI驱动
手机开户一般哪个证券公司好?究竟网上开户是否安全么?
通识篇:原型设计的认知,设计及最佳实践
Yolo nano: a highly compact one look convolutional neural network for target detection
programing language
UE4 编译单个文件(VS与编辑器分别启动)
Five heart charity matchmaker team
Open3d farthest point sampling (FPS)
Training view (issue temporary storage)