如何在JavaScript中使用Rest,默认和已分解参数对对象进行参数处理?
默认
这样可以轻松处理功能参数。轻松设置默认参数以允许使用默认值初始化形式参数。仅在未传递任何值或未定义的情况下才有可能。让我们看一个例子
示例
<html>
<body>
<script>
//默认设置为1-
function inc(val1, inc = 1) {
return val1 + inc;
}
document.write(inc(10,10));
document.write("<br>");
document.write(inc(10));
</script>
</body>
</html>休息
ES6带来了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>