首頁  >  文章  >  web前端  >  jquery可以遍歷array數組嗎

jquery可以遍歷array數組嗎

青灯夜游
青灯夜游原創
2021-11-16 14:06:382273瀏覽

jquery可以遍歷array數組,方法:1、利用for迴圈語句遍歷數組;2、利用「for in」迴圈語句遍歷數組;3、利用forEach()方法遍歷數組;4、利用each( )方法遍歷陣列;5、利用map()方法遍歷陣列。

jquery可以遍歷array數組嗎

本教學操作環境:windows7系統、jquery1.10.2版本、Dell G3電腦。

jquery遍歷array陣列

1、for迴圈:

var arr = new Array(13.5,3,4,5,6);
for(var i=0;i<arr.length><p>2、for in迴圈:</p><pre class="brush:js;toolbar:false;">var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
  document.write(mycars[x] + "<br />")
}

3、forEach方法遍歷

<script>
	var arr = [1,3,5,7,9];
	var obj = {0:1,1:3,2:5,3:7,4:9};
	/**
	*利用原生JS的forEach方法遍历
	*第一个参数:遍历到的元素
	*第二个参数:当前遍历到的索引
	*注意:原生的forEach方法只能遍历数组,而不能遍历伪数组
	*/
	arr.forEach(function(value,index){
		console.log("原生forEach遍历数组:",index,value);
	});
	/**
	obj.forEach(function(value,index){
		console.log("原生forEach遍历伪数组:",index,value);
		//Uncaught TypeError: obj.forEach is not a function
	});
	*/

</script>

jquery可以遍歷array數組嗎

4、each()遍歷陣列

<script>
	var arr = [1,3,5,7,9];
	var obj = {0:1,1:3,2:5,3:7,4:9};

	/**
	* 利用jQuery的each静态方法遍历
	* 第一个参数:当前遍历到的索引
	* 第二个元素:遍历到的元素
	* 注意:jQuery的each方法可以遍历伪数组
	*/
	$.each(arr,function(index,value){
		console.log("jQuery-each方法遍历数组:",index,value);
	})
	$.each(obj,function(index,value){
		console.log("jQuery-each方法遍历伪数组:",index,value);
	})
</script>

jquery可以遍歷array數組嗎

5、map()遍歷陣列

<script>
	var arr = [1,3,5,7,9];
	var obj = {0:1,1:3,2:5,3:7,4:9};
	/**
	*1.利用原生JS的map方法遍历 
	*第一个参数:遍历到的元素
	*第二个参数:当前遍历到的索引
	*第三个参数:当前被遍历的数组
	*注意:和原生的forEach方法一样,不能遍历伪数组
	*/
	arr.map(function(value,index,array){
		console.log("原生map遍历数组:",index,value,array);
	});
	/**
	obj.map(function(value,index,array){
		console.log("原生map遍历伪数组:",index,value,array);
		//Uncaught TypeError: obj.forEach is not a function
	});
	*/

	/**
	* 2.利用jQuery的each静态方法遍历
	* 第一个参数:要遍历的数组
	* 每遍历一个元素之后执行的回调函数
	* 回调函数的参数:
	* 	第一个参数:遍历到的元素
	* 	第二个元素:当前遍历到的索引
	* 注意:和jQuery的each方法一样可以遍历伪数组
	*/
	$.map(arr,function(value,index){
		console.log("jQuery-map方法遍历数组:",index,value);
	})
	$.map(obj,function(value,index){
		console.log("jQuery-map方法遍历伪数组:",index,value);
	})
</script>

jquery可以遍歷array數組嗎

相關教學推薦:jQuery影片教學

以上是jquery可以遍歷array數組嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn