數組 forEach、filter、map 理解

參考文檔

Array MDN數組

forEach、filter、map

1. forEach

1.1 參數

1.1.1 callback

用來測試數組的每一個元素的函數。調用時使用參數 (element, index, array)。
返回true表示保留該元素(經過測試),false則不保留。函數

1.1.2 thisArg

可選。執行 callback 時的用於 this 的值。測試

1.2 返回值

一個新數組,每一個元素都是回調函數的結果。this

1.3 範例

var arr = [1 , 2 , 3 , 4];
var thisArg = {name: 'grayVTouch'};
arr.forEach(function(val , index , arr){
    arr[index] = val.toUpperCase();
    console.log(this); // {name: 'grayVTouch'}
} , thisArg);

console.log(arr);

2. filter

2.1 參數

2.1.1 callback

用來測試數組的每一個元素的函數。調用時使用參數 (element, index, array)。
返回true表示保留該元素(經過測試),false則不保留。code

2.1.2 thisArg

可選。執行 callback 時的用於 this 的值。ip

2.2 返回值

一個新的經過測試的元素的集合的數組element

2.3 範例

var arr = [1 , 2 , 3 , 4];
var thisArg = {name: 'grayVTouch'};
var res = arr.filter(function(val , index , arr){
    console.log(this); // {name: 'grayVTouch'}
    
    if (val > 3) {
        return true;
    }
    
    return false;
} , thisArg);

console.log(arr);
console.log(res);

3. map

3.1 參數

3.1.1 callback

用來測試數組的每一個元素的函數。調用時使用參數 (element, index, array)。
返回true表示保留該元素(經過測試),false則不保留。文檔

3.1.2 thisArg

可選。執行 callback 時的用於 this 的值。get

3.2 返回值

一個新數組,每一個元素都是回調函數的結果。回調函數

3.3 範例

var arr = [1 , 2 , 3 , 4];
var thisArg = {name: 'grayVTouch'};
var res = arr.map(function(val , index , arr){
    console.log(this); // {name: 'grayVTouch'}
    return val + '數據測試';
} , thisArg);

console.log(arr);
console.log(res);
相關文章
相關標籤/搜索