陣列的foreach方法和jQuery中的each方法
阿新 • • 發佈:2018-12-04
陣列的foreach方法和jQuery中的each方法
/*
* 陣列的forEach方法:
* 1、返回給回撥的引數先是值,然後是下標
* 2、回撥函式執行時內部的this指向window
* */
/*var arr = [1,2,3,4,5];
arr.forEach(function( val, index ) {
console.log( val, index, this );
});*/
/* * jQ例項的each方法, * 1、返回給回撥的引數先是下標,然後是值 * 2、回撥函式執行時內部的this就指向遍歷到的每一個值(就是回撥中接收到的val) * 3、如果想中斷遍歷,在回撥中返回false即可 * */ /*$('li').each( function( index, val ) { console.log( index, val, this ); if( index === 1 ) { return false; } });*/
/* * jQ還提供了一個靜態版本的each方法,供框架使用者使用 * 1、返回給回撥的引數先是下標,然後是值 * 2、回撥函式執行時內部的this就指向遍歷到的每一個值(就是回撥中接收到的val) * 3、如果想中斷遍歷,在回撥中返回false即可 * */ var obj = { name: 'test', val: {} }; var arr2 = [ 'abc', {}, 'qwer' ]; $.each( obj, function( key, val ) { console.log( key, val, this ); } ); $.each( arr2, function( index, val ) { console.log( index, val, this ); } );