今天主要学习了对于higher order function及callbacks的理解,记录下自己的学习体会,以便日后复习。
1. 什么是higher order function
中文翻译成高阶函数,在数学和计算机科学中,高阶函数是至少具有下列功能之一的函数:
- Takes in a function or passes out a function
- Just a term to describe these functions - any function that does it we call that - but
there’s nothing different about them inherently
换句话说,可以简单理解成“the outer function that takes in a little baby function, or by the way returns out a function.
- 将一个或多个函数作为参数(即过程参数)。
- 返回一个函数作为结果。
2. 什么是Callbacks
What is callbakcs? Here is an explaination: The function we insert in is our callback function.
3. Examples
概念比较抽象,接下来用具体的例子来解释以下:
function copyArrayAndManipulate(array, instructions) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(instructions(array[i]));
}
return output;
}
function mutiplyByTwo(input){
return input*2;
}
const newArray =[1,2,3]
const result = copyArrayAndManipulate(newArray,mutiplyByTwo);
在上面这个简单计算一串array的二倍数并返回新array的代码中,我们可以看到:
- Higher order function: copyArrayAndManipulate function
- callbacks: multipleByTwo function
4. Appendix
在这里,顺便介绍以下arrow function, 以更简单的表达方式来写function
function multiplyBy2(input) { return input * 2; }
⇊
const multiplyBy2 = (input) => { return input*2 }
⇊
const multiplyBy2 = (input) => input*2
⇊
const multiplyBy2 = input => input*2
⇊
const output = multiplyBy2(3) //6
以上的function写法所得到的结果都是相同的
remember: All the designers of JavaScript love to reduce code. This is maybe for legibility, but maybe not for readability.
5. 练习实操
- Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs. BONUS: Use reduce!(求交集)
Your Answer Here
思路:
2. 首先实现能在两个array找到相同的数;
3. 再实现在多个数组中找到交集;
Answer
const intersection = (xs, ys) => xs.filter(x => ys.indexOf(x) > -1)
const intersectAll = (...xss) => xss.reduce(intersection);
intersectAll([5, 10, 15, 20, 3], [15, 88, 3, 1, 5, 7], [1, 10, 15, 5, 20,6], [3,4,6,7,5,15])
//[5,15]
- 求并集
Your answer Here
Answer:
function array_remove_repeat(array){
let newArray =[];
for(let i=0; i<array.length;i++){
let temp = array[i];
let flag = true;
for(let j=0;j<newArray.length;j++){
if(temp == newArray[j]){
flag =false;
break
} }
if(flag){
newArray.push(temp)
}
}
return newArray;
}
function array_union(a, b) { // 并集
return array_remove_repeat(a.concat(b));
}
const unionAll = (...xss) => xss.reduce(array_union);
unionAll([1,2,3,4],[56,7,3],[1,23,5])
//[1, 2, 3, 4, 56, 7, 23, 5]