jquery遍历方法each和map的区别

var arr = [1, 3, 5, 7, 9]
var obj = { 0: 1,1: 3,2: 5,3: 7,4: 9,length: 5}


    $.map(arr, function(value, index) {
        console.log(value, index);
    })
    $.map(obj, function(value, index) {
        console.log(value, index);
        })
        // 和jquery中的each一样,map方法可以遍历伪数组
    var res1 = $.map(obj, function(value, index) {
        console.log(value, index);
        return value + index    // [1, 4, 7, 10, 13]
 //map静态方法可以在回调函数中通过return对遍历的数组进行处理,然后生成一个新的数组返回
    })
    var res2 = $.each(obj, function(value, index) {
        console.log(value, index);
        return value + index   //{0: 1, 1: 3, 2: 5, 3: 7, 4: 9, length: 5}
// each静态方法不支持在回调函数中对遍历的数组进行处理
    })
    console.log(res1);
    console.log(res2);
    /*jQuery中的each静态方法和map静态方法的区别:
      each静态方法默认的返回值就是,遍历谁就返回谁
      map静态方法默认的返回值是一个空数组 */
posted @ 2021-06-15 21:24  YokeF  阅读(80)  评论(0编辑  收藏  举报