JS高階函數

JS高階函數介紹

高階函數

高階函數是對其餘函數進行操做的函數,能夠將它們做爲參數傳遞,或者是返回一個函數。 簡單來講,高階函數是一個接收函數做爲參數傳遞或者將函數做爲返回值輸出的函數。javascript

函數做爲參數傳遞

Array.prototype.map

map() 方法建立一個新數組,其結果是該數組中的每一個元素都調用一個提供的函數後返回的結果。不改變原數組java

🌰:面試

將一個數組 [1, 2, 3, 4] 中的每一項擴大2倍:數組

const arr1 = [1, 2, 3, 4]
const arr2 = arr1.map(item => item * 2)

console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [2, 4, 6, 8]
複製代碼

Array.prototype.filter

filter() 方法建立一個新數組, 其包含經過所提供函數實現的測試的全部元素。若沒有經過測試,則返回空數組;不改變原數組閉包

🌰: 對數組 [1, 3, 2, 4, 3, ,4 ,6, 3, 4, ,5 ,3 ,1] 進行去重處理:函數

const arr1 = [1, 3, 2, 4, 3, ,4 ,6, 3, 4, ,5 ,3 ,1]
const arr2 = arr1.filter((item, index, self) => {
    return self.indexOf(item) === index
})
console.log(arr1) // [1, 3, 2, 4, 3, ,4 ,6, 3, 4, ,5 ,3 ,1]
console.log(arr2) // [1, 3, 2, 4, 6, 5]
複製代碼

Array.prototype.reduce

語法: arr.reduce(callback[, initialValue])測試

reduce() 方法對數組中的每一個元素執行一個由您提供的reducer函數(升序執行),將其結果彙總爲單個返回值。ui

reduce() callback函數接受四個參數:spa

  1. accumulator(acc) (累加器)
  2. currentValue(cur)(當前值)
  3. currentIndex(idx)(當前索引) (可選)
  4. array(arr)(原數組) (可選)

reduce 函數的返回值分配給累計器,該返回值在數組的每一個迭代中被記住,並最後成爲最終的單個結果值。prototype

initialValue 初始值(可選)。

做爲第一次調用 callback函數時的第一個參數的值。 若是沒有提供初始值,則將使用數組中的第一個元素。 在沒有初始值的空數組上調用 reduce 將報錯。

🌰:累加案例

  • 無初始值
const arr = [1, 2, 3, 4, 5]
let sum = arr.reduce((acc, cur, idx, arr) => {
    return acc + cur
})

console.log(sum) // 15
複製代碼
  • 有初始值
const arr = [1, 2, 3, 4, 5]
let sum = arr.reduce((acc, cur, idx, arr) => {
    return acc + cur
}, 10)

console.log(sum) // 25
複製代碼

函數做爲返回值輸出

簡單說就是返回一個函數。

isType 函數

判斷函數類型經常使用的是 Object.prototype.toString.call() 來獲取對應對象返回的字符串;

eg:

console.log(Object.prototype.toString.call('hello world')); // [object String]
複製代碼

能夠對類型判斷進行封裝成一個 isType 方法:

let isType = type => obj => {
  return Object.prototype.toString.call(obj) === '[object ' + type + ']'
}

console.log(isType('String')('hello'))     // true
console.log(isType('Number')(123))         // true
console.log(isType('Array')([1, 2, 3]))   // true
console.log(isType('Object')({
  name: 'Tom'
}))    // true

複製代碼

這裏就是一個高階函數,由於 isType 函數將 obj => { ... } 這一函數做爲返回值輸出。

add 函數

打印函數時會自動調用 toString() 方法。eg:

let sum = function () {
  return 1 + 2
}

console.log(sum)
// ƒ() {
// return 1 + 2
// }

sum.toString = function () {
  return 12
}

console.log(sum) // f 12
console.log(sum.toString()) // 12

// 打印函數的時候會自動調用 toString 方法,所以能夠重寫 toString 方法來修改返回值;

複製代碼

面試題, 用 JS 實現一個無限累加的函數 add。

add(1).toString()   // 1
add(1)(2).toString() // 3
add(1)(2)(3).toString() // 6

複製代碼

實現:

function add(a) {
    function sum(b) { // 閉包
        a = a + b
        return sum
    }
    
    sum.toString = function () { // 重寫 toString 方法
        return a
    }
    
    return sum
}
console.log(add(1)) // f 1 (function)
console.log(add(1).toString()) // 1
console.log(add(1)(2).toString()) // 3

複製代碼
相關文章
相關標籤/搜索