使用jQuery迭代JavaScript对象的属性

时间:2009-07-08 08:53:33

标签: javascript jquery for-loop iteration

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

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

我只是不喜欢这个for从我可爱的jQuery符号中伸出来!

4 个答案:

答案 0 :(得分:206)

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

each

答案 1 :(得分:54)

您也可以将each用于对象,而不仅仅用于数组:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});

答案 2 :(得分:9)

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

function enumerate(o,s){

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

    //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"){

            //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");});

答案 3 :(得分:3)

迟到,但可以使用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;
&#13;
<ul id="object-keys"></ul>
&#13;
&#13;
&#13;