1.学习目标
对于数组在js中除了for循环遍历还有foreach和借用map遍历,这一小节我们就来了解下js中的foreach,map和jQuery中的each和map的区别
2.代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery-3.1.1.min.js" ></script>
</head>
<body>
<script type="text/javascript">
var arr=[12,34,64,6,4,7,8,9,2];
var obj={1:10,2:100,3:1000,4:10000};
//JS中的forEach遍历输出
/*arr.forEach(function(index,value){
console.log(value);
})*/
//JS中的调用map输出
// 注意参数的顺序,首先传入的是value然后是index
/*arr.map(function(value,index){
console.log(index+":"+value);
})*/
//原生js不能遍历object对象
/* obj.forEach(function(index,value){
console.log(value);
})*/
//原生js不能遍历object对象
/* obj.map(function(value,index){
console.log(index+":"+value);
})*/
//利用jQuery中的each相当于原生js中的forEach
/* $(arr).each(function(index,value){
console.log(value);
})*/
//使用jQuery中的each可以遍历伪数组
/* $(obj).each(function(index,value){
console.log(value);
})*/
//利用jQuery中的map相当于原生js中的map
/* $(arr).map(function(index,value){
console.log(index+":"+value);
})*/
//使用jQuery中的map可以遍历伪数组
/* $(obj).map(function(index,value){
console.log(value);
})*/
</script>
</body>
</html>
3.总结
1.在原生的js中foreach和map只能便利数组,不能便利对象
2.在js中的map调用时要注意参数的顺序,先试value,才是index
3.jQuery中的each和map能够便利数组和伪数组,同时节省了代码量