1

JavaScript 函数默认参数

 1 year ago
source link: https://www.myfreax.com/javascript-default-parameters/
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.
JavaScript 函数默认参数

JavaScript 默认参数

在本教程中,您将学习如何在 JavaScript 使用 ES6 函数的默认参数。

function say(message='Hi') {
    console.log(message);
}

say(); // 'Hi'
say('Hello') // 'Hello'

say() 函数中 message 参数的默认值是 'Hi'

在 JavaScript ,如果没有值或者 undefined 传递给函数,默认函数参数允许您使用默认值初始化命名参数。

实参与形参

Parameters 中文是形参,Arguments 的中文是实参,你可以将实参 Arguments 理解为形参的实际值。有时,您可以互换使用术语实参和形参。。

但是,根据定义,形参是您在函数声明中指定的名称,而实参是您传递给函数的内容。考虑以下 add() 函数:

function add(x, y) {
   return x + y;
}

add(100,200);

在这个例子中,xy 是函数的形参,传递给 add() 函数的值 100 和 200 是实参。

为函数设置 JavaScript 默认参数

在 JavaScript ,参数的默认值为 undefined。这意味着如果您不将参数传递给函数,其参数的值是 undefined

例如以下示例:

function say(message) {
    console.log(message);
}

say(); // undefined

say() 函数接受参数 message。因为我们没有向函数传递任何实参,所以 say() 函数的 message 参数的值为 undefined

假设你想将 message 参数给一个默认值 10。实现此目的,最常用的方法是测试参数值是否是 undefined 并使用三元运算符分配默认值:

function say(message) {
    message = typeof message !== 'undefined' ? message : 'Hi';
    console.log(message);
}
say(); // 'Hi'

在这个例子中,我们没有向 say() 函数传递任何值。因此,message 参数的默认值为 undefined。在函数内部,我们将字符串重新分配给 message 变量 Hi

ES6 为您提供了一种更简单的方法来设置函数参数的默认值,如下所示:

function fn(param1=default1, param2=default2,..) {
}

在上面的语法中,您使用赋值运算符 = 和值在参数名称后面为参数设置默认值。例如:

function say(message='Hi') {
    console.log(message);
}

say(); // 'Hi'
say(undefined); // 'Hi'
say('Hello'); // 'Hello'

代码是如何运行的。

  • 在第一个函数调用中,我们没有向 say() 函数传递任何参数,因此 message 参数采用默认值 'Hi'
  • 在第二次函数调用中,我们将 undefined 传递给 say() 函数,因此 message 参数也采用了默认值 'Hi'
  • 在第三个函数调用中,我们将字符串传递 'Hello'say() 函数,因此message 参数将字符串 'Hello' 作为值。

JavaScript 默认参数示例

让我们看一些更多的例子来了解一些用于设置函数参数默认值的可用选项。

传递未定义的参数

以下  createDiv() 函数在 document 创建一个具有指定高度、宽度和边框样式的 <div> 元素:

function createDiv(height = '100px', width = '100px', border = 'solid 1px red') {
    let div = document.createElement('div');
    div.style.height = height;
    div.style.width = width;
    div.style.border = border;
    document.body.appendChild(div);
    return div;
}

现在尝试不向 createDiv() 函数传递任何参数,因此 createDiv() 函数使用参数的默认值。

createDiv();

假设您要使用高度和宽度参数的默认值以及指定的边框样式。在这种情况下,您需要将 undefined 值传递给前两个参数。如下所示:

createDiv(undefined,undefined,'solid 5px blue');

表达式默认参数

JavaScript 引擎会在您调用函数时评估默认参数。请阅读以下示例:

function put(toy, toyBox = []) {
    toyBox.push(toy);
    return toyBox;
}

console.log(put('Toy Car'));
// -> ['Toy Car']
console.log(put('Teddy Bear'));
// -> ['Teddy Bear'], 不是 ['Toy Car','Teddy Bear']

考虑以下示例:

function date(d = today()) {
    console.log(d);
}
function today() {
    return (new Date()).toLocaleDateString("en-US");
}
date();

date() 函数接受一个参数,其默认值是 today() 函数的返回值。today() 函数以指定的格式返回今天日期的字符串。

当我们声明 date() 函数时,today() 函数在我们调用 date() 函数之前尚未被运行。

我们可以使用这种方式使参数成为强制性的。如果调用者没有传递任何参数,我们将抛出如下错误:

function requiredArg() {
   throw new Error('The argument is required');
}
function add(x = requiredArg(), y = requiredArg()){
   return x + y;
}

add(10); // error
add(10,20); // OK

在默认值中使用其他参数

您可以为参数分配一个默认值,后面的参数可以引用前面的参数的默认值。如以下示例所示:

function add(x = 1, y = x, z = x + y) {
    return x + y + z;
}

console.log(add()); // 4

add() 函数:

  • y 的默认值设置为 x 参数的默认值。
  • z 的默认值是 xy 的和
  • add() 函数返回 xyz 总和。

参数列表有自己的作用域。如果引用还没有初始化的参数,就会报错。例如:

function subtract( x = y, y = 1 ) {
    return x - y;
}
subtract(10);

错误信息 Uncaught ReferenceError: Cannot access 'y' before initialization ,翻译过来就是未捕获的引用错误,不能够访问 y 在 y 初始化之前:

Uncaught ReferenceError: Cannot access 'y' before initialization

使用函数作为默认值

您可以使用函数的返回值作为参数的默认值。例如:

let taxRate = () => 0.1;
let getPrice = function( price, tax = price * taxRate() ) {
    return price + tax;
}

let fullPrice = getPrice(100);
console.log(fullPrice); // 110

getPrice()函数,我们调用 taxRate() 函数获取税率,并使用此税率从价格中计算出税额。

函数内部 arguments 对象的值是您传递给函数的实际参数的数量。例如:

function add(x, y = 1, z = 2) {
    console.log( arguments.length );
    return x + y + z;
}

add(10); // 1
add(10, 20); // 2
add(10, 20, 30); // 3

现在,您应该了解 JavaScript 默认函数参数以及如何有效地使用它们。

微信公众号

支付宝打赏

myfreax 淘宝打赏

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK