0
点赞
收藏
分享

微信扫一扫

JavaScript-函数形参默认值

在 ES6 之前可以通过逻辑运算符来给形参指定默认值,格式: 条件A || 条件B,如果条件 A 成立, 那么就返回条件 A,如果条件 A 不成立, 无论条件 B 是否成立, 都会返回条件 B。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
function getSum(a, b) {
a = a || "BNTang";
b = b || "www.it6666.top";
console.log(a, b);
}

getSum(123, "abc");
</script>
</head>
<body>
</body>
</html>

从 ES6 开始, 可以直接在形参后面通过 ​​=​​ 指定默认值,????注意点: ES6 开始的默认值还可以从其它的函数中获取。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript">
function getSum(a = "JonathanLee", b = getDefault()) {
console.log(a, b);
}

getSum();

function getDefault() {
return "BNTang";
}
</script>
</head>
<body>
</body>
</html>




举报

相关推荐

0 条评论