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);
});
js的forEach、map及jq的each
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.