回答

收藏

检测未定义的对象属性

技术问答 技术问答 259 人阅读 | 0 人回复 | 2023-09-12

检查 JavaScript 未定义对象属性的最佳方法是什么?
( n- {8 ]2 M3 b6 z. J; c3 s3 Q                                                               
" Q. m9 f2 ~$ j9 C    解决方案:                                                               
! h* D9 a# B7 D* L                                                                检查属性值是否为特殊值的常用方法undefined是:% N5 G# W! Y) Z# c! M- l
    if(o.myProperty === undefined) {  alert("myProperty value is the special value `undefined`");}
    $ V- u* y8 Q1 [0 N6 S
检查对象是否实际上没有这样的属性,因此undefined当您尝试访问它时,默认返回:
  j! }4 y% W3 X1 m9 x
    if(!o.hasOwnProperty('myProperty) {  alert("myProperty does not exist");}
    ) n$ v2 x! l* X* o
检查与标识符相关的值是否为特殊值undefined,或者标识符是否尚未声明。注意:这种方法是引用未声明(注:与 值不同undefined)唯一没有早期错误的方法:
3 _2 E! H' {, V9 ^/ y" e

    ) k* K) h7 W9 H0 g; Y* T. L- Y8 K
  • if(typeof myVariable === 'undefined') {  alert('myVariable is either the special value `undefined`,or it has not been declared」code]在 ECMAScript 5 以前的 JavaScript 版本中,全局对象被称为undefined属性是可写的,所以foo === undefined如果不小心重新定义了一个简单的检查,可能会发生意外。JavaScript 中,这个属性只读。
    & m6 p1 t6 ~% ^8 [' h% p; ~* K) R
  • 但在现代 JavaScript 中,未定义不是关键词,因此函数中的变量可以命名为未定义,并隐藏整体属性。
    & l7 x6 R9 U* T+ H
  • 如果你担心这种边缘(不太可能),你可以使用它void 获得特殊操作符undefined值本身:[code]if(myVariable === void alert("myVariable is the special value `undefined`");}
    , v/ z! O5 S. p% f9 F( w
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则