循环使用相同的密钥JSON节点

时间:2013-02-20 11:44:50

标签: javascript jsonp

我正试图在JSON块中吐出用户的所有场景,但我遗漏了一些东西......

你想看看吗?

我也把它放在这里: http://jsfiddle.net/RBergante/2HwEH/

这就是我所拥有的:

function scenes(){
    var allscenes = new Array();
    for (var i in data.users){
        allscenes = data.users[i].scenes.scene;
        document.write(allscenes[i] + "</br>");
    }
}

var data={"users":[
    {
        "firstName":"Rick",
        "lastName":"Villalobos",
        "pic":"http://ia.media-imdb.com/images/M/MV5BMTg2NTEyNTE3NF5BMl5BanBnXkFtZTcwNjY3NzM0OA@@._V1._SY209_CR1,0,140,209_.jpg",
        "scenes": {
            "scene": "In the Woods",
            "scene": "City lights",
            "scene": "Marnon Willis"                        
        },
        "joined": {
            "month":"January",
            "day":12,
            "year":2012
        }
    },
    {
        "firstName":"John",
        "lastName":"Jones",
        "pic":"http://ia.media-imdb.com/images/M/MV5BMTU4MDA1NDU1NV5BMl5BanBnXkFtZTcwMjYzNTYxOA@@._V1._SY209_CR0,0,140,209_.jpg",
        "joined": {
            "month":"April",
            "day":28,
            "year":2010
        }
    }   
]}

scenes();

谢谢!

1 个答案:

答案 0 :(得分:1)

因为对象不能具有同一个键的多个属性。场景应该是一个数组:

"scenes": ["In the Woods", "City lights", "Marnon Willis"]

http://jsfiddle.net/2HwEH/1/

  • 此外,在循环遍历数组时,请不要使用for-in,因为它还将运行数组属性,而不仅仅是索引内容。请改用forwhile

  • 此外,您不应该使用document.write(),尤其是在页面加载完成后(例如,稍后在函数中调用)。