一、jQuery对象和伪数组
<html lang="en"> <head> <meta charset="UTF-8"> <title>hhahah
title> <script src="jquery-1.12.4.min.js">
script> <script> $(function(){
var $div = $("div"); console.log($div); var arr = [1,3,5]; console.log(arr); });
script>
head> <body> <div>div1
div> <div>div2
div> <div>div3
div>
body>
html>
<script> var arr = [1,3,5,7,9]; var obj = {
0:1,1:3,2:5,3:7,4:9}; / *1.利用原生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 }); */ / * 2.利用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>
<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>

总结:
1.原生的map方法只能遍历数组,而不能遍历伪数组
2.jQuery的map方法可以遍历伪数组
四、each()方法 和 map()方法的区别
<script> var obj = {
0:1,1:3,2:5,3:7,4:9}; / * jQuery中的each静态方法和map静态方法的区别 * each 静态方法默认的返回值就是,遍历谁就返回谁 * map 静态方法的返回值是,一个空数组 * each方法静态方法不支持在回调函数中对遍历的数组进行处理 * map 静态方法可以在回调函数中通过return对遍历的数组进行操作,生成一个新的数组返回 */ var $res1 = $.each(obj,function(index,value){
}); var $res2 = $.each(obj,function(index,value){
return index + value; }); var $res3 = $.map(obj,function(value,index){
}); var $res4 = $.map(obj,function(value,index){
return value + index; }); console.log("each方法返回值:",$res1); console.log("map方法返回值:",$res3); console.log("map方法操作后返回值:",$res2); console.log("map方法操作后返回值:",$res4); </script>
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/206590.html原文链接:https://javaforall.net
