[Original] Similarities and differences between each and $.each in jquery

One, the similarities and differences between each and $.each

  1. The same point: both are traversal methods;
  2. Different points : each traverses the dom object; $.each traverses the data source (array or object)

 

Second, each traverses the dom instance:

What kind of DOM is suitable for traversal?
Answer: For repeated and regular DOM , we can traverse the value through each; this keyword points to a different DOM element (each time is a different matching element)

html is as follows:

<div class="row">
	<div class="col-md-3">宝马</div>
	<div class="col-md-3">奥迪</div>
	<div class="col-md-3">大众</div>
	<div class="col-md-3">别克</div>
</div>
<table>
	<tr>
		<td>宝马</td>
		<td>奥迪</td>
		<td>大众</td>
		<td>别克</td>
	</tr>
</table>

js is as follows: 

//遍历dom结构--------------------------------------------------------------
	
		//针对重复有规律的dom,我们可以通过each来遍历获值;this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。
		$(".row .col-md-3").each(function(){
			console.log($(this).text())
		})
		
		$("table td").each(function(){
			console.log("这个是表格输出的信息:"+$(this).text())
		})
		

		//获取的值,放到什么位置呢?2个选择,数组或者是对象中。
		var arr_01 = [];
		$(".row .col-md-3").each(function(){
			arr_01.push($(this).text());
		})
		console.log(arr_01)

The return value is as follows:

Three, $.each traverses the data source instance:

  • data source score group or object,
  • When traversing objects, pay special attention because objects are: key/value pairs; i in the code below is actually the key of the object, and val is the value of the object.
//遍历数组--------------------------------------------------------------
		//遍历一维数组
		var arr_02 =['big','chai','cool'];
		$.each(arr_02,function(i,val){ //注意2点,①遍历数组比dom遍历前面多了一个$符号和逗号;②2个参数,i是数组索引号;val是数组值
			console.log("索引号为:"+i+";"+"值为:"+val);
		})
		
		//遍历二维数组
		var arr_03=[['柴','玉龙'],['陈','大伟'],['王','小蛋']];
		$.each(arr_03,function(i,val){ 
			console.log("索引号为:"+i+";"+"值为:"+val);
		})
		
		//如何取到姓?
		$.each(arr_03,function(i,val){ 
			console.log("索引号为:"+i+";"+"姓为:"+val[0]);//val[0]取值为值里面的第1个值
		})
		
		
	
//遍历对象--------------------------------------------------------------
		var obj ={
			name:"大柴叔",
			age:18,
			phone:"apple",
			city:"宁波"
		};
		
		$.each(obj,function(i,val){ 
			console.log("键:"+i+";"+"值:"+val); //因为对象是:键/值 构成;这里的i其实是对象的键,val是对象的值。
		})

The return value is as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325338323&siteId=291194637