回答

收藏

检测未定义的对象属性

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

检查 JavaScript 未定义对象属性的最佳方法是什么?. n# ~- J! L( m% ^9 `
                                                                7 M( [" \% Q+ l7 h
    解决方案:                                                               
5 t7 x! W( _4 g  u& Q                                                                检查属性值是否为特殊值的常用方法undefined是:. ^& s8 O- O1 Z% t% x
    if(o.myProperty === undefined) {  alert("myProperty value is the special value `undefined`");}  K1 |2 Y  @9 p0 r9 C+ L; {4 B8 }" c
检查对象是否实际上没有这样的属性,因此undefined当您尝试访问它时,默认返回:
& X. @( S1 O9 l9 H5 `! H- B( N  A( C
    if(!o.hasOwnProperty('myProperty) {  alert("myProperty does not exist");}' f) H" x- m7 i" ?) m
检查与标识符相关的值是否为特殊值undefined,或者标识符是否尚未声明。注意:这种方法是引用未声明(注:与 值不同undefined)唯一没有早期错误的方法:5 |# _, E; r( n3 N; n

    3 _0 o4 Z" y8 ~, r* r) o1 n' n
  • 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 中,这个属性只读。) q4 l6 M4 B- K! \  f
  • 但在现代 JavaScript 中,未定义不是关键词,因此函数中的变量可以命名为未定义,并隐藏整体属性。* r+ |5 J& z, j  J4 u" T0 e7 F
  • 如果你担心这种边缘(不太可能),你可以使用它void 获得特殊操作符undefined值本身:[code]if(myVariable === void alert("myVariable is the special value `undefined`");}
    ) }( E/ J; w/ M6 }: Z5 ~6 p
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则