回答

收藏

检测未定义的对象属性

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

检查 JavaScript 未定义对象属性的最佳方法是什么?
1 Z1 W! I, M8 i5 t; C9 r' y                                                               
1 U3 I, F. T6 ]1 G8 [5 {    解决方案:                                                                7 w8 p) d7 W' n; M" Z0 s& {
                                                                检查属性值是否为特殊值的常用方法undefined是:
% x6 K  f+ b( u7 l) y4 m( D  V7 N# `
    if(o.myProperty === undefined) {  alert("myProperty value is the special value `undefined`");}
    # ], l$ `  n+ W( [- O% ]
检查对象是否实际上没有这样的属性,因此undefined当您尝试访问它时,默认返回:* D5 O7 h  V% n7 I9 x* j' j" _
    if(!o.hasOwnProperty('myProperty) {  alert("myProperty does not exist");}
    + z$ B' s. o7 e" |3 M. ~
检查与标识符相关的值是否为特殊值undefined,或者标识符是否尚未声明。注意:这种方法是引用未声明(注:与 值不同undefined)唯一没有早期错误的方法:4 ?  ~$ x' j& L7 @3 ]
    * e3 f2 A- L$ q+ S
  • 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 中,这个属性只读。. w! b/ w: P; i" ]+ L; C
  • 但在现代 JavaScript 中,未定义不是关键词,因此函数中的变量可以命名为未定义,并隐藏整体属性。7 S- D2 c7 S- V6 z, X: M; c6 l
  • 如果你担心这种边缘(不太可能),你可以使用它void 获得特殊操作符undefined值本身:[code]if(myVariable === void alert("myVariable is the special value `undefined`");}( F' @: _1 Y" R9 g) e/ g
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则