使用jQuery迭代JavaScript对象的属性

tag*_*s2k 115 javascript iteration jquery for-loop

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

    for (var member in obj) {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*the 206

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

  • 每个都有更多的功能:`this`也是`n`.`return false`打破了每个循环...... (4认同)
  • @Eugene:我不明白你的观点.每个函数将数组或对象作为第一个参数,将函数作为第二个参数.此函数为数组中的每个元素/对象中的每个属性获取calld.每次调用该函数时,它都会获取作为参数传入的索引和值/名称和值.在我的例子中,参数"n"是两个字符串"John"和"JS"."name"属性将是"undefined". (2认同)

Gum*_*mbo 55

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

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


jon*_*der 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));
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

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

var response = $.ajax({
    url: myurl,
    dataType: "json"
})
.done(function(a){
   console.log("Returned values:");
   enumerate(a);
})
.fail(function(){ console.log("request failed");});
Run Code Online (Sandbox Code Playgroud)