如何在 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>
廣告