jq用法——2-map和each遍历(注:js原生forEach仅可遍历数组,不可遍历伪数组)

版权声明:转发博客 请注明出处 否则必究 https://blog.csdn.net/lucky541788/article/details/81981519
$(function () {
            /*
            map和each都可对数组和伪数组遍历,而js原生forEach仅可遍历数组,不可遍历伪数组
            map,each的区别
            map静态方法默认返回值是一个空数组
            each静态方法默认返回值是,遍历谁就返回谁

            each不支持在回调函数对遍历数组进行处理
            map支持在回调函数中通过return对遍历数组进行处理,然后生成一个新的数组返回
             */
            var a=[3,4,5,7,8];
            var a1=$.each(a,function (index,value) {
                console.log(index, value);//0 3;1 4;2 5;3 7;4 8;
            });
            var a2=$.map(a,function(value,index){
                console.log(index,value);//0 3;1 4;2 5;3 7;4 8;
                return index+value;
            });
            console.log(a1);//(5) [3, 4, 5, 7, 8]
            console.log(a2);//(5) [3, 5, 7, 10, 12]

            var b={4:4,5:3,6:9,length:4};
            var c1=$.each(b,function (index,value) {
                console.log(index, value);//4 4;5 3;6 9;length 4
            });
            var c2=$.map(b,function(value,index){
                console.log(index,value);//4 4;5 3;6 9;length 4
                return index+value;
            });
            console.log(c1);//{4: 4, 5: 3, 6: 9, length: 4}
            console.log(c2);//(4) ["44", "53", "69", "length4"]
        })
    </script>

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/81981519
今日推荐