Answers:
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
this
也n
。return false
打破了每个循环……
此方法将遍历对象属性,并以递增的缩进量将它们写入控制台:
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");});
较晚,但是可以通过使用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>
n
并非完全正确。至少可能是n.name