How to loop through key/value object in Javascript? [duplicate]

瘦欲@ 提交于 2019-11-28 17:20:40

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}
for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!