For循环迭代对象

时间:2015-01-20 16:31:53

标签: javascript object for-loop

var questions = {
game: {
    question_1: {
        question: "Question 1",
        points: 7
    },
    question_2: {
        question: "Question 2",
        points: 5
    }
}
};

编程新手......

如何使用for循环迭代我的问题对象来访问questions.game.question_1.question?或questions.game.question_ [n] .question

var answers = [];

for(var i=0; i <questions.game.length; i++) {
questions.game.question_[i].question.push(answers);
}

1 个答案:

答案 0 :(得分:1)

像这样:

for (var key in questions.game) {
    if (questions.game.hasOwnProperty(key)) {
        questions.game[key].question.push(answers);
    }
}

另一方面,当您尝试将push数组放入字符串时,您会遇到一些麻烦。你倒退了吗?

for (var key in questions.game) {
    if (questions.game.hasOwnProperty(key)) {
        answers.push(questions.game[key].question);
    }
}