11

「JS-Learning」ES5与ES6中如何处理不确定参数 - ES5中的arguments_ES6中的Rest参数 -...

 3 years ago
source link: https://www.wenyuanblog.com/blogs/javascript-uncertain-parameters-in-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

「JS-Learning」ES5 与 ES6 中如何处理不确定参数

不定参数,即向函数传递的参数数目不固定,JavaScript 中 ES5 和 ES6 不定参数的写法不同。

ES5 中处理不定参数(arguments)

javascript
function sum() { let sum = 0 Array.from(arguments).forEach(function(item) { sum += item }) return sum } console.log(sum(1, 2, 3, 4)) // 10

ES6 中处理不定函数(Rest参数)

ES6 引入Rest参数(形式为 ...变量名),用于获取函数的多余参数,这样就不需要使用 arguments 对象了。

Rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中。故Rest参数理解为「剩下的所有参数」。

javascript
function sum(...num) { let sum = 0 Array.from(num).forEach(function(item) { sum += item }) return sum } console.log(sum(1, 2, 3, 4)) // 10

Rest参数的强大之处

  • Rest参数可以将确定的参数在传值时分离出来(此时Rest参数必须排在参数最后),而如果使用 arguments 需在函数内部进行分离操作。看下面这个例子:
javascript
function sum(a, ...num) { //这里的a代表确定参数,可以有多个确定参数 let sum = 0 Array.from(num).forEach(function(item) { sum += item }) return a * 2 + sum } console.log(sum(1, 2, 3, 4, 5)) // 16
  • arguments 不是数组,所以不能直接使用数组的原生 API 如 forEach,而Rest参数是数组,可以直接使用数组的原生 API。对比下面两个例子:
javascript
// 使用 arguments function sum() { let num = 0 Array.prototype.forEach.call(arguments, function(item) { num += item * 1 }) return num } console.log(sum(1, 2, 3)) // 6 console.log(sum(1, 2, 3, 4)) // 10
javascript
// 使用Rest参数 function sum(...nums) { let num = 0 nums.forEach(function(item) { num += item * 1 }) return num } console.log(sum(1, 2, 3)) // 6 console.log(sum(1, 2, 3, 4)) // 10

Rest参数与扩展运算符

在 ES6 中,Rest参数和扩展运算符都用符号 ... 来表示,但是表达的确实相反的意思。

Rest参数是将不定的参数「收敛」到数组中,而扩展运算符是将固定的数组内容「打散」到参数里去。

Rest参数与扩展运算符可以理解为互为逆运算。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK