js的forEach、map及jq的each

        var arr = ['Nice', 'to', 'meet', 'you', '!'];
        var res = arr.map(function (value, idx, array) {
            console.log(value, idx, array, this); //Nice 0 Array(5) [ "Nice", "to", "meet", "you", "!" ] Window
            //支持return
            console.log(array === arr); //true
            return idx + '-' + value;
        });

        console.log(res); //Array(5) [ "0-Nice", "1-to", "2-meet", "3-you", "4-!" ]

       /*
        *    currentValue:数组中正在处理的当前元素
        *    index:数组中正在处理的当前元素的索引
        *    array:forEach()方法正在操作的数组
        *    var res1 = arr.forEach(function (currentValue, index, array) {
        *       console.log(index, array === arr); //true
        *       console.log(currentValue); //Nice to meet you !
        *       array[index] = index;
        *       console.log(array);
        *       console.log(this); //window
        *       console.log(this);//Array(5) [ "0-Nice", "1-to", "2-meet", "3-you", "4-!" ]
        *    });
             console.log(res1); //返回值undefined
        **/
        /*
         * jQ还提供了一个静态版本的each方法,供框架使用者使用
         * 1、返回给回调的参数先是下标,然后是值
         * 2、回调函数执行时内部的this就指向遍历到的每一个值(就是回调中接收到的val)
         * 3、如果想中断遍历,在回调中返回false即可(在each代码块内不能使用break和continue,替代方法 break:return false; continue:return true)
         * */
        $.each(arr,function(index,val){
            console.log('hhhh',index,val,this);
        });

        $('li').each(function(index,val){
            console.log('hhhh',index,val,this);
        });

猜你喜欢

转载自blog.csdn.net/gzkahjl/article/details/82884063
今日推荐