Javascript:从数组中的对象中选择属性

时间:2015-04-06 07:43:15

标签: javascript arrays object

我有一个对象数组,我想在该数组中选择某个对象的属性。当我尝试以下代码时,它不起作用,我在字符串中没有得到任何值:

var _string = teams[2].name;

在数组代码下面:

var teams = new Array (team1, team 2, team3);

var team1 = {
     name: "team 1",
     matches: 5 
}


var team2 = {
     name: "team 2",
     matches: 4 
}


var team3 = {
     name: "team 3",
     matches: 3 
}

一些帮助会很棒: - )

由于

2 个答案:

答案 0 :(得分:3)

你应该首先宣布你的团队和你的阵列如下:

var team1 = {
     name: "team 1",
     matches: 5 
}

var team2 = {
     name: "team 2",
     matches: 4 
}

var team3 = {
     name: "team 3",
     matches: 3 
}

var teams = [team1, team2, team3];

另请注意,代码中team2之间的空格不正确。

答案 1 :(得分:0)

错误var teams = new Array (team1, team 2, team3);,应为var teams = new Array (team1, team2, team3);

您在team2之间添加了不必要的空格:)