jquery循环遍历数组
遍历数组的基本方法
使用jQuery的$.each()方法可以方便地遍历数组。该方法接受两个参数:要遍历的数组或对象,以及一个回调函数。回调函数中的第一个参数是索引,第二个参数是当前元素的值。
var arr = ['apple', 'banana', 'orange'];
$.each(arr, function(index, value) {
console.log('Index: ' + index + ', Value: ' + value);
});
遍历数组并操作DOM
结合DOM操作时,可以动态生成元素。例如将数组内容输出到ul列表中:
var fruits = ['Apple', 'Banana', 'Cherry'];
var $list = $('#fruit-list');
$.each(fruits, function(i, fruit) {
$list.append('<li>' + fruit + '</li>');
});
使用jQuery的map方法
$.map()方法会返回一个新数组,可以对原数组元素进行转换:
var numbers = [1, 2, 3];
var squared = $.map(numbers, function(num) {
return num * num;
});
console.log(squared); // [1, 4, 9]
遍历对象数组
当数组元素是对象时,可以访问对象属性:
var users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 }
];
$.each(users, function(i, user) {
console.log(user.name + ' is ' + user.age + ' years old');
});
提前终止循环
在$.each()中返回false可以终止循环,相当于普通循环中的break:
var nums = [1, 2, 3, 4, 5];
$.each(nums, function(i, num) {
if(num > 3) return false;
console.log(num);
});
跳过当前迭代
在$.each()中返回true可以跳过当前迭代,相当于普通循环中的continue:

var nums = [1, 2, 3, 4, 5];
$.each(nums, function(i, num) {
if(num === 3) return true;
console.log(num);
});






