118

是否有一种 jQuery 方法来对对象的成员执行迭代,例如:

    for (var member in obj) {
        ...
    }

我只是不喜欢这个for从我可爱的 ​​jQuery 符号中脱颖而出!

4

4 回答 4

214
$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

每个

于 2009-07-08T08:59:16.787 回答
56

您也可以使用each对象,而不仅仅是数组:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});
于 2009-07-08T09:01:21.853 回答
9

注意:大多数现代浏览器现在允许您在开发者控制台中导航对象。这个答案已经过时了。

此方法将遍历对象属性并将它们写入控制台并增加缩进:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //if o is null, we need to output and bail
    if(typeof o == "object" && o === null){

       console.log(s+k+": null");

    } else {    

        //iterate across o, passing keys as k and values as v
        $.each(o, function(k,v){

            //if v has nested depth
           if(typeof v == "object" && v !== null){

                //write the key to the console
                console.log(s+k+": ");

                //recursively call enumerate on the nested properties
                enumerate(v,s+"  ");

            } else {

                //log the key & value
                console.log(s+k+": "+String(v));
            }
        });
    }
}

只需将要迭代的对象传递给它:

    var response = $.ajax({
        url: myurl,
        dataType: "json"
    })
    .done(function(a){
       console.log("Returned values:");
       enumerate(a);
    })
    .fail(function(){ console.log("request failed");});
于 2013-01-09T17:06:52.027 回答
4

晚了,但可以通过使用Object.keys来完成,例如,

var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},
  ulkeys=document.getElementById('object-keys'),str='';
var keys = Object.keys(a);
for(i=0,l=keys.length;i<l;i++){
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';
}
ulkeys.innerHTML=str;
<ul id="object-keys"></ul>

于 2016-02-08T11:28:41.393 回答