如何访问数组中的JavaScript对象?

时间:2019-05-28 18:28:32

标签: javascript

我的问题是如何访问数组中的对象。例如,如何访问属性country

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}]

2 个答案:

答案 0 :(得分:2)

访问array objects中的property的正确语法是:

array[index].objectProperty

因此,要访问第一个索引的国家/地区值,您应该使用:

arr1[0].country  // Schweiz

例如,让我们打印出阵列上的每个国家/地区:

var arr1 = [{
    country: "Schweiz",
    code: 'ch'
  },
  {
    country: "Deutschland",
    code: 'de'
  },
  {
    country: "Oesterreich",
    code: 'at'
  }
];

arr1.forEach((item)=>{
  document.write(item.country+"<br>");
})

  

注意: 您提供的数组结构中存在语法错误。您缺少逗号,该逗号用于分隔数组中的元素。

数组是用逗号分隔的结构,如下所示:

myArray = [1,2,3,4,5];

因此,要分隔每个索引,您需要使用逗号。你有:

var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    }, // First separator comma
    {
        country: "Deutschland",
        code: 'de'
    } { // MISSING COMMA HERE
        country: "Oesterreich",
        code: 'at'
    }

]

因此,只需用逗号分隔新元素:

var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    },
    {
        country: "Deutschland",
        code: 'de'
    }, // ADDED COMMA
    {
        country: "Oesterreich",
        code: 'at'
    }

]

希望这对您的问题有所帮助。欢迎使用Stackoverflow。

答案 1 :(得分:0)

如果您知道索引,则只需使用索引

arr1[1].country;

如果要按国家/地区代码查找,可以找到它

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}];

const getCountry = (array, code) => array.find(country => country.code === code);

console.log(getCountry(arr1, 'de'));

相关问题