旧行李
2009-03-26 06:01
采纳率: 25%
浏览 592
已采纳

我如何循环或枚举一个 JavaScript 对象?

I have a JavaScript object like the following:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Now I want to loop through all p elements (p1, p2, p3...) And get their keys and values. How can I do that?

I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval.

转载于:https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

29条回答 默认 最新

  • 10.24 2009-03-26 06:12
    已采纳

    You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

    Here is the snippet:

    var p = {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3"
    };
    
    for (var key in p) {
        if (p.hasOwnProperty(key)) {
            console.log(key + " -> " + p[key]);
        }
    }

    </div>
    
    评论
    解决 无用
    打赏 举报
查看更多回答(28条)

相关推荐 更多相似问题