Javascript 使用for而不是jQuery each
我希望使用for循环,而不是$each。怎么样 我的代码为$。每个代码如下:Javascript 使用for而不是jQuery each,javascript,jquery,ajax,each,Javascript,Jquery,Ajax,Each,我希望使用for循环,而不是$each。怎么样 我的代码为$。每个代码如下: $.ajax({ type: "POST", url: 'get_units', data: { id : '1'}, success: function (units) { $.each(units, function (index, val) { //I want change this line to for loop alert(index
$.ajax({
type: "POST",
url: 'get_units',
data: { id : '1'},
success: function (units) {
$.each(units, function (index, val) { //I want change this line to for loop
alert(index+'-'+val) // I want two result
});
},
"error": function (x, y, z) {
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
试试这个
for(i = 0; i < units.length; i++) {
alert(i+'-'+units[i]);
}
如果有对象,可以使用:
var units = {
'a': 'Hello',
'b': 'World'
};
for (var prop in units) {
console.log(prop);
console.log(units[prop]);
}
如果您有阵列,请使用:
使用for循环有什么问题?$。每个函数有什么问题?@SKG an$。每个函数都增加了可能不必要的复杂性,因为一方面需要为每个迭代执行函数调用,另一方面可能会创建新的作用域。因此,将$更改为FOR可能是一个可以理解的想法。您可以在每个函数中将第二个参数值作为范围值传递,以避免创建范围。请注意:在for…in循环中,我不会称之为index,而是key、prop或类似的东西。As index对于数组的使用更为常见,它指示0范围内的数值。。n@t.niese很好,完成了;。
var units = ['Hello', 'World'];
for (var i = 0, l = units.length; i < l; i++) {
console.log(i);
console.log(units[i]);
}