首页 > 代码库 > 取对象的属性时,用“.”还是“[]”

取对象的属性时,用“.”还是“[]”

例1:

function phoneticLookup(val) {

  var result = "";

  var lookup = {

    "alpha":"Adams",

    "bravo":"Boston",

    "charlie":"Chicago",

    "delta":"Denver",

    "echo":"Easy",

    "foxtrot":"Frank"

  };

  result = lookup.val;

      console.log(result);         ==》  undefined

  return result;

}

//调用函数

phoneticLookup ("alpha");

 

例2:

function phoneticLookup(val) {

  var result = "";

  var lookup = {

    "alpha":"Adams",

    "bravo":"Boston",

    "charlie":"Chicago",

    "delta":"Denver",

    "echo":"Easy",

    "foxtrot":"Frank"

  };

  result = lookup[val];

      console.log(result);            ==》  Adams

  return result;

}

//调用函数

phoneticLookup ("alpha");

 

注意:如果你需要通过变量来访问对象的属性值,请用中括号操作符,点操作符不支持变量。

 

取对象的属性时,用“.”还是“[]”