高阶函数之函数作为参数使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// function f1(fn){
// console.log("f1的函数");
// // 此时fn当成是一个函数来使用的
// fn();
// }
// fn是参数,最后作为函数使用了,函数是可以作为参数使用
// 传入匿名函数
// f1(function(){
// console.log("我是匿名函数");
// });
// 命名函数
// function f2(){
// console.log("f2的函数");
// }
// f1(f2);
// 函数作为参数的时候,如果是命名函数,那么只传入命名函数的名字,没有括号
function f1(fn){
setInterval(function(){
console.log("定时器开始");
fn();
console.log("定时器结束");
},1000);
}
// f1(function(){
// console.log("好困,好饿");
// });
</script>
</head>
<body>
</body>
</html>
高阶函数之函数作为返回值使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// function f1(){
// console.log("f1函数开始");
// return function(){
// console.log("我是函数,但是此时是作为返回值使用的");
// }
// console.log("f1函数结束");
// }
// var ff = f1();
// ff();
// var num = 10;
// // 获取num这个变量的数据类型
// console.log(typeof num);
// // 对象
// var obj = {};
// console.log(obj instanceof Object);
// // 获取某个对象的数据类型的样子
// // 此时得到的就是这个对象的类型的样子
// // Object.prototype.toString.call(对象);
// // 此时输出的是Object的数据类型
// console.log(Object.prototype.toString());
// // 输出数组的数据类型 [Object Array]
// console.log(Object.prototype.toString.call([]));
// var arr = [10,20];
// console.log(Object.prototype.toString.call(arr));
// console.log(Object.prototype.toString.call(new Date()));
// 获取某个对象的类型是不是你传入的类型
// [10,20] 是不是[object Array]
// type----是变量---是参数----"[object Array]"
// obj----是变量----是参数----[10,20]
// 判断这个对象和传入的类型是不是同一个类型
function getFunc(type){
return function(obj){
return Object.prototype.toString.call(obj)===type;
}
}
// var ff = getFunc("[object Array]");
// var result = ff([10,20]);
// console.log(result);
var ff = getFunc("[object Date]");
var result = ff(new Date());
console.log(result);
</script>
</head>
<body>
</body>
</html>
函数作为参数的练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
// var arr = [1,5,8,63,14,6,45];
// // 排序
// arr.sort();
// console.log(arr);
var arr = [1,5,8,63,14,6,45];
// // 排序--函数作为参数使用,匿名函数作为sort方法的参数使用
// // 那么此时的匿名函数中有两个参数,
arr.sort(function(obj1,obj2){
if(obj1>obj2){
return 1;
}else if(obj1==obj2){
return 0;
}else{
return -1;
}
});
console.log(arr);
var arr = ["acdf","abcd","bcedf","bced"];
arr.sort(function(a,b){
if(a>b){
return 1;
}else if(a==b){
return 0;
}else{
return -1;
}
});
console.log(arr);
</script>
</head>
<body>
</body>
</html>