如何确定对象在JavaScript中是否具有给定属性 [英] How to determine whether an object has a given property in JavaScript

查看:117
本文介绍了如何确定对象在JavaScript中是否具有给定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定对象 x 是否具有已定义的属性 y ,无论<$的值如何c $ c> xy ?

How can I determine whether an object x has a defined property y, regardless of the value of x.y?

我目前正在使用

if (typeof(x.y) !== 'undefined')

但是这看起来有点笨拙。有更好的方法吗?

but that seems a bit clunky. Is there a better way?

推荐答案

对象有财产:



如果您正在测试对象本身的属性(不是其原型链的一部分),您可以使用 .hasOwnProperty()

if (x.hasOwnProperty('y')) { 
  // ......
}



对象或其原​​型有一个属性:



你可以使用 in 运算符测试继承的属性。

Object or its prototype has a property:

You can use the in operator to test for properties that are inherited as well.

if ('y' in x) {
  // ......
}

这篇关于如何确定对象在JavaScript中是否具有给定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆