龙空技术网

jQuery是可以遍历数组和伪数组(对象)的

少儿编程scratch 124

前言:

如今我们对“jquery截取数组前5个”大约比较重视,看官们都需要分析一些“jquery截取数组前5个”的相关资讯。那么小编同时在网摘上搜集了一些对于“jquery截取数组前5个””的相关资讯,希望看官们能喜欢,我们快快来了解一下吧!

jQuery是可以遍历数组和伪数组(对象)的

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>09-静态方法-each方法</title>

<script src="../static/js/jquery-3.6.0.js"></script>

<script>

// 定义一个数组

arr = [1, 3, 5, 7, 9]

// 定义个伪数组,就是一个对象

let obj = {0:1, 1:3, 2:5, 3:7, 4:9, length:5};

// 原生遍历数组的方法

// value第一个参数:遍历到的元素

// index第二个参数:当前遍历到的索引

// 原生的foreach方法只能遍历数组,不能遍历伪数组

console.log("----------------------下面是原生的foreach方法遍历数组----------------------")

arr.forEach(function(value, index){

console.log("索引为:",index," 值为:", value)

})

console.log("索引为:",index," 值为:", value)运行结果

// 原生的foreach遍历伪数组只能报错

console.log("----------------下面是原生的foreach方法遍历伪数组(对象)----------")

obj.forEach(function(value, index){

console.log("索引为:",index," 值为:", value)

})

console.log("索引为:",index," 值为:", value)运行结果

console.log("----------------------下面是利用jQuery遍历数组------------------------")

// 利用jQuery遍历数组 $.each(要遍历的数组, 回调函数(索引, 值){执行的语句})

// index第一个参数: 当前遍历到的索引

// value第二个参数: 遍历到的元素

// jQuery是可以遍历数组和伪数组(对象)的

$.each(arr, function(index, value){

console.log("索引为:",index," 值为:", value);

});

console.log("索引为:",index," 值为:", value);运行结果

console.log("----------------------下面是利用jQuery遍历伪数组(对象)------------")

$.each(obj, function(index, value){

console.log("索引为:",index," 值为:", value);

});

console.log("索引为:",index," 值为:", value);运行结果

</script>

</head>

<body>

</body>

</html>

标签: #jquery截取数组前5个