当前位置:网站首页>转载 :判断对象是否具有属性的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。
用法:

边栏推荐
- Macros, functions, and inline functions
- Jar package and war package
- Hb5470 combustion test of non-metallic materials in civil aircraft cabin
- Augfpn: improved multiscale feature learning for target detection
- AugFPN:改进多尺度特征学习用于目标检测
- UE4 installs the datasmith plug-in in version 4.20-23
- ISO16000-9建筑产品和家具中挥发性有机物的测试
- UE4 插件报错 Cannot open include file: ‘ModuleManager.h‘解决
- UE4 在4.20-23版本安裝Datasmith插件
- easyexecl导出100万行execl报字体错误的解决办法
猜你喜欢

Training kernel switching using GPU

Yotact real-time instance segmentation

Simplicity studio does not recognize the new JLINK V9 solution

Share code snippets of wechat applet

长安链GO语言智能合约编写与编译

Augfpn: amélioration de l'apprentissage des caractéristiques à plusieurs échelles pour la détection des cibles

Record the field name dynamically modified by SetData of wechat applet

Visual assist plug-in settings for UE4 vs

Instance error iopub data rate exceeded

UE4 remove the mask transparent white edge in the material
随机推荐
两阶段目标检测原理详细版
The difference between cokkie and session
Twinmotion 初学者教程
Visual assist plug-in settings for UE4 vs
Twinmotion beginner tutorial
Wechat applet opens file stream
Wechat applet sharing page, sharing to the circle of friends
爱快安装或重置后,PC或手机端获取不到ip
UE4 在4.20-23版本安装Datasmith插件
云管理平台:OpenStack架构设计及详细解读
LSM6DSL之SPI驱动
Iso16000-9 testing of volatile organic compounds in building products and furniture
Recursive RBAC menu level display infinite classification
The principle of session and cookie
【数据集】|标注的bbox影响 Can we trust bounding box annotations for object detection
UE4 VS的Visual Assist插件设置
SPI drive of lsm6dsl
Pytoch Summary - transform between sensor and numpy
YOLO Nano:一种高度紧凑的只看一次的卷积神经网络用于目标检测
数据处理时代,数据质量建设才是企业的生存之道