JavaScript JSON中的访问对象属性

时间:2014-07-31 19:09:16

标签: javascript json object

我正在研究一些基本的对象项目,以便使用它们并绑定JSON。但是,我遗失了一些东西,因为我一直被归还' undefined'尝试访问嵌套属性时。

目标是创建一个新的场景对象,并根据我传递的场景名称加载内容。

function newScene(name) {
    var sceneName = name;

    this.sceneDetails = function() {

        var theDetails = {
            "home": [
                { "title": "Home Page",
                "desc": "This home page is the homiest of all home pages." }
            ],
            "about": [
                { "title": "The About Page",
                "desc": "This page is about stuff." }
            ]
        }
        console.log(theDetails[sceneName]['title']);
    }
}


var thePage = new newScene('home');
var thePageBuild = thePage.sceneDetails();

在执行此操作时,我会被给予' undefined'而不是实际的主页标题。任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

您正在为数组添加标题和说明,因此实际的详细信息位于

console.log(theDetails[sceneName][0]['title']);

我怀疑这不是你想要的,所以将theDetails赋值改为this,代码应该可以正常工作:

var theDetails = {
    "home": { 
        "title": "Home Page",
        "desc": "This home page is the homiest of all home pages."
    },
    "about": { 
        "title": "The About Page",
        "desc": "This page is about stuff." 
    }            
}

答案 1 :(得分:0)

试试这个

function newScene(name) {
    var sceneName = name;

    this.sceneDetails = function() {

        var theDetails = {
            "home": [
                { "title": "Home Page",
                "desc": "This home page is the homiest of all home pages." }
            ],
            "about": [
                { "title": "The About Page",
                "desc": "This page is about stuff." }
            ]
        }
        console.log(theDetails[sceneName][0].title);
    }
}


var thePage = new newScene('home');
var thePageBuild = thePage.sceneDetails();

这是有效的fiddle

答案 2 :(得分:0)

因为你有家和设置为数组,你需要像这样访问它们:

console.log(theDetails[sceneName][0]['title']);

或像这样重组json:

   var theDetails = {
        "home": 
            { "title": "Home Page",
            "desc": "This home page is the homiest of all home pages." },
        "about": 
            { "title": "The About Page",
            "desc": "This page is about stuff." }

    }