从对象

时间:2017-07-15 13:37:58

标签: javascript

我有一个这样的对象:

var obj = [
{
    "id": 728,
    "title": "A long day",
    "images": {
        "illustration": {
            "title": "Preview",
            "16x9": {
                "1248x702": "https://example.com/image/225944d77559.jpg",
                "1920x1080": "https://example.com/image/4546b05422594.jpg"
            }
        }
    }
}
];

我正在尝试获得1920x1080值,但没有成功:

            alert(obj[0].title); //works 
            alert(obj[0].images.illustration.title); // works 
            alert(obj[0].images.illustration.16x9.1920x1080); // doesn't work and break the code
            alert(obj[0].images.illustration.'16x9'.'1920x1080'); // doesn't work and break the code

我需要你的帮助。我该怎么做才能正确输入1920x1080?

3 个答案:

答案 0 :(得分:1)

使用括号:



var obj = [
{
    "id": 728,
    "title": "A long day",
    "images": {
        "illustration": {
            "title": "Preview",
            "16x9": {
                "1248x702": "https://example.com/image/225944d77559.jpg",
                "1920x1080": "https://example.com/image/4546b05422594.jpg"
            }
        }
    }
}
];

console.log(obj[0].images.illustration['16x9']['1920x1080']);




答案 1 :(得分:0)

试试这个,

alert(obj[0].images.illustration['16x9']['1920x1080']);

答案 2 :(得分:0)

你应该写下:

obj[0].images.illustration['16x9']['1920x1080']

在JS中,如果你有具有特定同义词的对象键,你应该将它包装在方括号[' 1920x1080']中,就像你从数组中得到elemet一样。