如何在 JavaScript 中使用 Rest、默认和解构参数来参数对象?
javascriptweb developmentfront end technology
default
这可以轻松处理函数参数。轻松设置默认参数以允许使用默认值初始化形式参数。这仅在未传递任何值或未定义时才有可能。让我们看一个例子
示例
<html>
<body>
<script>
// default 设置为 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 中引入的用于与模式匹配绑定的参数。如果未找到该值,则返回未定义。让我们看看 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>
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

