javascript 如何避免属性访问错误

var book = {subtitle: "Bible"};  

var bookName = book.name.length // 这时候会出错,  因为试图查询这个不存在的对象的属性就会报错

以下提供两种避免出错的方法:

1.

var len = undefined;

if(book) {

  if(book.name) len = book.name.length;

}

2. 一种更简洁的常用方法, 获取name的length属性或者undefined

var len = book && book.name && book.name.length;   // 不会报错, len = undefined

检测属性方法: 

可以通过in运算符, hasOwnProperty()方法, propertyIsEnumerable()方法来完成这个工作.

1. in运算符的左侧是属性名(字符串), 右侧是对象. 如果对象的自有属性或继承属性中包含这个属性则返回true. 

  var o = { x: 1 }
  "x" in o; // true: o has an own property "x"
  "y" in o; // false: o doesn't have a property "y"
  "toString" in o; // true: o inherits a toString property

2. 对象的hasOwnProperty()方法用来检测给定的名字是否是对象的自有属性, 对于继承属性它将返回false.

  var o = { x: 1 }
  o.hasOwnProperty("x"); // true: o has an own property x
  o.hasOwnProperty("y"); // false: o doesn't have a property y
  o.hasOwnProperty("toString"); // false: toString is an inherited property


3. propertyIsEnumerable()是hasOwnProperty()的增强版, 只有检测到是自有属性且这个属性的可枚举性为true的时候它才返回true. 

  var o = inherit({ y: 2 });
  o.x = 1;
  o.propertyIsEnumerable("x"); // true: o has an own enumerable property x
  o.propertyIsEnumerable("y"); // false: y is inherited, not own
  Object.prototype.propertyIsEnumerable("toString"); // false: not enumerable

原文地址:https://www.cnblogs.com/facial/p/5101875.html