如何在 JavaScript 中使用 Rest、默认值和解构参数对 arguments 对象进行参数处理?
默认值
它能够轻松处理函数参数。轻松设置默认值参数,允许使用默认值初始化形式参数。只有在没有传递值或传递 undefined 的情况下才可能实现这一点。让我们看一个示例
示例
<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 参数,减轻了开发人员的工作。对于 arguments 对象,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