1.设置默认值
ES5的实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function add (a ,b) {
if (b == undefined) {
b = 10;
}
console.log(a+b);
}
add(10,20);
add(10);
</script>
</body>
</html>
运行结果: HTML4.png
ES6的实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function add (a, b = 10) { //b的默认值为10
console.log(a+b);
}
//一般设置默认值为尾参数,若我们要将a设为默认值,则不能省略,需要站位
function add2 (a = 10, b = 10) { //b的默认值为10
console.log(a+b);
}
add(10,20);
add(10);
add2(undefined,20);
</script>
</body>
</html>
网友评论