标签:[] case def 重复 init ice ati call har
1、简述
高阶函数似乎是一种先进编程的的技术。然而,并不是。
高阶函数其实就是将函数作为参数或者返回值的函数。其中作为参数的函数一般是回调函数。
2、例子
(1)最简单的例子
大家都熟悉数组的sort方法。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>高阶函数</title>
</head>
<body>
<script type="text/javascript">
let arr = [1,2,4,3];
arr.sort((a,b)=>{return a-b})
console.log(arr)
</script>
</body>
</html>
sort方法的参数就是一个函数(回调函数),这个回调函数决定了如何比较数组中的任意两个元素。
(2)字符换大写
实现一:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>高阶函数</title>
</head>
<body>
<script type="text/javascript">
let arr = [‘abc‘, ‘def‘],
arrNew = [];
for(let i = 0; i < arr.length; i++) {
arrNew[i] = arr[i].toUpperCase()
}
console.log(arrNew)
</script>
</body>
</html>
实现二:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>高阶函数</title>
</head>
<body>
<script type="text/javascript">
let arr = [‘abc‘, ‘def‘],
arrNew = [];
arrNew = arr.map(val => {
return val.toUpperCase()
})
console.log(arrNew)
</script>
</body>
</html>
(3)高阶函数实现
若代码中出现重复或者类似的代码,就可以使用高阶函数。如产生一个包含数字的字符串:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>高阶函数</title>
</head>
<body>
<script type="text/javascript">
let digits = ‘‘
for (let i=0;i<10;i++) {
digits += i
}
console.log(digits)
</script>
</body>
</html>
使用高阶函数实现:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>高阶函数</title>
</head>
<body>
<script type="text/javascript">
let digits = ‘‘
function buildString(n, callback) {
let val = ‘‘;
for(let i = 0; i < n; i++) {
val += callback(i)
}
return val
}
digits = buildString(10, i => {
return i
})
console.log(digits)
</script>
</body>
</html>
标签:[] case def 重复 init ice ati call har
原文地址:https://www.cnblogs.com/mengfangui/p/9812654.html