callback学习笔记
2019-03-12 本文已影响3人
一书文集
let x = function(){
console.log('xxxxx');
};
let y = function(callback){
console.log('yyyyyy');
// console.log(callback); // there var "callback" = x,because x inside
callback(); // call the x function
};
y(x);
// Example 1 例题一和例题二对比学习.
//1.first edition;
let calc = function(num1, num2, calcType){
if(calType === "add"){
return num1 + num2;
}else if(calType = "multiply"){
return num1 * num2;
};
};
console.log(calc(2,3,multiply))
//2. with callback
//add function there
let add = function(a, b){
return a + b
};
//multiply
let multiply = function(a, b){
return a * b
};
// the main function there
let calc = function(num1, num2, callback){
return callback(num1, num2); //if callback it's add, then it's equal to return add(num1, num2)
};
console.log(calc(2,3,multiply))
// 2. with callback doWhatever
//add function there
let add = function(a, b){
return a + b
};
//multiply
let multiply = function(a, b){
return a * b
};
// dowhater passin as variable results
let doWhatever = function(a, b){
//String interpolation:
console.log('here are your two numbers back ${a}, ${b}');
};
// the main function there
let calc = function(num1, num2, callback){
return callback(num1, num2); //if callback it's add, then it's equal to return add(num1, num2)
};
//!!!!!
console.log(cal(2,3, function(a, b) {
return a -b;
}));
//The BAD SITUATION, callback must be a function name, if not, there will be wrong things happen, it the calc have to use "if condition";
let calc = function(num1, num2, callback){
if(type of callback === function){
return callback(num1, num2);
}
}
// Example: 2
// The callback in sortfunction
var myArr = [{
num: 5,
str: 'apple'
},{
num: 7,
str: 'ban'
}];
//we can change str to num, to get the sort results we want
myArr.sort(function(val1, val2){
if(val1.str > val2.str){
return -1;
}else {
return 1;
}
})
console.log(myArr);
// Example 3
//选出大于5的内容with callback
var list = [5, 8, 9, 2, 7, 5];
function callback(list){
var newList = [];
for(var i =0; i<list.length; i++){
if(list[i]>5){
newList.push(list[i]);
}
return newList;
}
function filter(list, callback){
return callback(list);
}
}
let filtered = filter(list, callback);
console.log(filtered);
学数据结构后看这些东西感觉特别简单... 觉得自己学早了前端...