当前位置:网站首页>js对象:检测属性是否存在
js对象:检测属性是否存在
2022-07-21 09:11:00 【你吃香蕉吗?】
目录
一、in
in运算符左侧是属性名(字符串),右侧是对象。
如果对象的自由属性或继承属性中又这个属性则返回true
// 例
let obj = {x:1};
"x" in obj; // true:x是obj的自有属性
"y" in obj; // false:y不是obj的自有属性,也不是obj的继承属性
"toString" in obj; // true:obj继承toString属性
二、hasOwnPreperty()
hasOwnPreperty方法用来检测给定的名字是否是对象的自有属性,对于继承属性它将返回false
// 例
let obj = {x:1};
obj.hasOwnProperty("x"); // true:x是obj的自有属性
obj.hasOwnProperty("y"); // false:obj上不存在y属性
obj.hasOwnProperty("toString"); // false:toString是继承属性,不是自有属性
三、propertyIsEnumerable()
propertyEnumerable()是hasOwnproperty()的增强版,只有检测到时自有属性且这个属性的可枚举性(enumerable attribute)为true时,它才返回true。
<script>
function School(schoolName) {
this.school = schoolName
}
function Student(major, name) {
this.major = major
this.name = name
}
Student.prototype = new School('西安交通大学');
let xiaoMing = new Student('计算机科学与技术', '小明')
console.log(xiaoMing);
xiaoMing.propertyIsEnumerable('name'); // true: xiaoming有一个可枚举的自有属性
xiaoMing.propertyIsEnumerable('school'); // false: school是继承来的
</script>
四、!== 或===
直接判断属性是否是undefined
注意:当属性值为undefined时,这种判断方式是不能区分不存在的属性和存在但值为undefined的属性,如果需要区分,需要使用in来判断
<script>
let obj = {
name: undefined
}
obj.name !== undefined; // false: 属性存在,但值为undefined
obj.age !== undefined; // false: 属性不存在
</script>
边栏推荐
- Matlab simulation analysis of spectrum switching mechanism of cognitive radio based on relay assistance
- AtCoder Beginner Contest 260 - C, D, E
- 3511. 倒水问题
- Leetcode 206反转链表、3无重复字符的最长子串、912排序数组(快排)、215数组中的第k个最大元素、53最大子数组和、152乘积最大子数组
- rose
- m在ISE平台下使用verilog开发基于FPGA的GMSK调制器
- A thorough understanding of bio, NiO, AIO
- 【FreeRTOS】10 事件标志组
- m在simulink进行DS-CDMA建模,然后通过MATLAB调用simulink模型进行误码率仿真
- 架构模式 节选自《闻缺陷则喜》(此书可免费下载)
猜你喜欢
C # use resx manager to switch between Chinese and English
SkyWalking服务端的搭建、微服务接入SkyWalking
Codeforces Round #808 (Div. 2) - A,B,C
[deep learning notes] attention mechanism
利用正则回溯最大次数上限进行绕过
第3章业务功能开发(实现显示线索主页面,并查询表单各个下拉框数据)
Pytorch common code snippet collection
Gateway整合Sentinel实现对路由的限流规则
为Kubernetes选择合适的容器运行时
Judgment of empty string in Oracle
随机推荐
07.02 Huffman code
架构模式 节选自《闻缺陷则喜》(此书可免费下载)
Hcip day 10 notes
基于php开发的学生成绩管理系统
抓住晨会驱动【目标管理】
Musk uploaded his brain to the cloud? Zhou Hongyi: we have to use human brain security guards to kill poison
Sentinel容错规则持久化
过时 2 天后,微软放弃“封禁”商业开源!
一文让你掌握22个神经网络训练技巧
How to use the order flow analysis tool (Part 1)
Codeforces Round #809 (Div. 2) - C, D1
Multiple ways of sorting tablewidgets
反沙箱方法
Feign详解,日志配置+契约设置+超时时间+自定义拦截器
童年的回忆小游戏来了——贪吃蛇,快来自己动手写一个属于自己的小游戏吧
VALDO2021——血管病变检测挑战赛之血管间隙分割(二)
rust中的静态分发和动态分发
URLEncode.encode(String,String) 和 new String(byte[],String) 的区别
VALDO2021——血管病变检测挑战赛之血管间隙分割(一)
优炫数据库如何查看一个存储过程的执行计划