如何在 JavaScript 中使用 Rest、默认和解构参数对参数对象进行参数化?
默认
这有助于轻松处理函数参数。轻松设置默认参数,允许使用默认值初始化形式参数。只有在没有传入值或值未定义时才可能做到这一点。让我们看一个示例:
示例
<html>
<body>
<script>
// default is set to 1
function inc(val1, inc = 1) {
return val1 + inc;
}
document.write(inc(10,10));
document.write("<br>");
document.write(inc(10));
</script>
</body>
</html>rest
ES6 引入 rest 参数,减轻开发者的工作量。对于参数对象,rest 参数用三个点(...)表示,并放在参数之前。
示例
让我们看下面的代码段:-
<html>
<body>
<script>
function addition(…numbers) {
var res = 0;
numbers.forEach(function (number) {
res += number;
});
return res;
}
document.write(addition(3));
document.write(addition(5,6,7,8,9));
</script>
</body>
</html>解构
ES6 中引入的参数用于与模式匹配绑定。如果未找到该值,则返回 undefined。让我们看看 ES6 如何允许将数组解构为单独的变量
示例
<html>
<body>
<script>
let marks = [92, 95, 85];
let [val1, val2, val3] = marks;
document.write("Value 1: "+val1);
document.write("<br>Value 2: "+val2);
document.write("<br>Value 3: "+val3);
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP