Javascript:在数组中构造一个数组并使用console.log

时间:2016-06-04 14:56:09

标签: javascript arrays object console.log

我在JavaScript课程中,并按照以下说明进行了分配:

  1. 创建一个数组并将此数组指定给名为“presidents”的变量。

  2. 在此数组中,创建五个对象,每个对象具有以下属性:

    • 的firstName

    • lastName的

    • termLength

    • yearsOfPresidency

  3. 为每个人填写适当的信息 五位最近的美国总统。

  4. 使用console.log(),alwaysnts变量和数组表示法注销第三位总统的名字和姓氏(这应该注明“Bill Clinton”)。

  5. 这是我到目前为止所做的:

    
    
    var presidents: [{
      firstName: 'Barak',
      lastName: 'Obama',
      termLength: '8 years',
      party: 'Democratic',
      yearsOfPresidency: '2009-Present'
    }, {
      firstName: 'George W.',
      lastName: 'Bush',
      termLength: '8 years',
      party: 'Republican',
      yearsOfPresidency: '2001-2009'
    }, {
      firstName: 'Bill',
      lastName: 'Clinton',
      termLength: '8 years',
      party: 'Democratic',
      yearsOfPresidency: '1993-2001'
    }, {
      firstName: 'George H. W.',
      lastName: 'Bush',
      termLength: '4 years',
      party: 'Repuplican',
      yearsOfPresidency: '1989-19934'
    }, {
      firstName: 'Ronald',
      lastName: 'Reagan',
      termLength: '8 years',
      party: 'Republican',
      yearsOfPresidency: '1981-1989'
    }]
    
    console.log(presidents(1, 1));
    
    
    

    所以,我知道我可能甚至没有接近,而且我有一个错误(我不知道如何解决。)

    我的问题是:

    1. 如何删除错误?
    2. 如何正确地让console.log返回"比尔克林顿?"
    3. 你有什么其他建议我可能太无知了吗?
    4. 谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用总统访问数组中的第3项[2] 然后使用presidents [2] .propertyname

访问其中的任何属性

在您的示例总统[2] .firstName,总统[2] .lastName

答案 1 :(得分:0)

你写了var presidents :并且是var presidents =

要控制日志 Bill Clinton ,您需要这样做:

const bill = presidents[2];
console.log(bill.firstName+" "+bill.lastName);

所有片段:

var presidents = [{
  firstName: 'Barak',
  lastName: 'Obama',
  termLength: '8 years',
  party: 'Democratic',
  yearsOfPresidency: '2009-Present'
}, {
  firstName: 'George W.',
  lastName: 'Bush',
  termLength: '8 years',
  party: 'Republican',
  yearsOfPresidency: '2001-2009'
}, {
  firstName: 'Bill',
  lastName: 'Clinton',
  termLength: '8 years',
  party: 'Democratic',
  yearsOfPresidency: '1993-2001'
}, {
  firstName: 'George H. W.',
  lastName: 'Bush',
  termLength: '4 years',
  party: 'Repuplican',
  yearsOfPresidency: '1989-19934'
}, {
  firstName: 'Ronald',
  lastName: 'Reagan',
  termLength: '8 years',
  party: 'Republican',
  yearsOfPresidency: '1981-1989'
}]


const bill = presidents[2];
console.log(bill.firstName + " " + bill.lastName);