freeCodeCamp/guide/chinese/certifications/javascript-algorithms-and-d.../basic-javascript/accessing-nested-arrays/index.md

1.2 KiB
Raw Blame History

title localeTitle
Accessing Nested Arrays 访问嵌套数组

访问嵌套数组

使用括号表示法[]访问数组中的元素

var fruitBasket = ['apple', 'banana' 'orange', 'melon']; 
 var favoriteFruit = fruitBasket[2]; 
 
 console.log(favoriteFruit) // 'orange' 

在这个例子中,我们最喜欢的水果是'orange',它位于fruitBasket数组的索引2 。使用braket表示法我们将fruitBasket数组的索引2分配给favoriteFruit 。这使得favoriteFruit等于'orange'。

使用braket []和dot访问数组中的对象.符号

var garage = [ 
  { 
    type: 'car', 
    color: 'red', 
    make: 'Ford' 
  }, 
  { 
    type: 'motorbike', 
    color: 'black', 
    make: 'Yamaha' 
  }, 
  { 
    type: 'bus', 
    color: 'yellow', 
    make: 'Blue Bird' 
  } 
 ]; 
 
 var busColor = garage[2].color; // 'yellow' 

解:

// Setup 
 var myPlants = [ 
  { 
    type: "flowers", 
    list: [ 
      "rose", 
      "tulip", 
      "dandelion" 
    ] 
  }, 
  { 
    type: "trees", 
    list: [ 
      "fir", 
      "pine", 
      "birch" 
    ] 
  } 
 ]; 
 
 // Only change code below this line 
 
 var secondTree = myPlants[1].list[1];