zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Accessing Objects Properties with Variables #251

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

250 使用[ ]

249 使用.

中括号[ ]的另一种使用方法是使用变量来访问对象属性。

方法

伪代码

变量=属性名称;
对象={
   属性名称:值;
}
对象[变量]   //值

样例1

var someProp = "propName";
var myObj = {
    propName : "Some Value"
}
myObj[someProp];// "Some Value"

样例2

var myDog= "Hunter";
var dogs =  {
  Fido: "Mutt",
  Hunter: "Doberman",
  Snoopie: "Beagle"
};
var breed= dogs[myDog];
console.log(breed);  //"Doberman"

注意,当我们访问属性时,变量两边不加引号,因为我们用的是变量的值,而不是名称。

练习

Use the playerNumber variable to lookup player 16 in testObj using bracket notation.

代码


// Setup
var testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

// Only change code below this line;

var playerNumber=16;       // Change this Line
var player = testObj[playerNumber];   // Change this Line

结果显示

image

来源

https://www.freecodecamp.org/challenges/accessing-objects-properties-with-variables