迭代使用jQuery JavaScript对象的属性迭代使用jQuery JavaScript对象的

2019-05-17 14:28发布

是否有一个jQuery的方式来过一个对象的成员,如在执行迭代:

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

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

Answer 1:

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



Answer 2:

您可以使用each只为数组的对象太多,而不是:

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


Answer 3:

此方法将穿行对象的属性,并将其写入与增加缩进控制台:

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


Answer 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> 



文章来源: Iterating a JavaScript object's properties using jQuery