繁体   English   中英

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

[英]How can I access JavaScript object in array?

我的问题是如何访问数组中的对象。 例如,我如何进入物业country

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

访问对象 数组 属性的正确语法是:

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。

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

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')); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM