了解JavaScript中的默认参数

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

作者选择了COVID-19救济基金来接受捐赠,这是Write for DOnations计划的一部分。

介绍 (Introduction)

In ECMAScript 2015, default function parameters were introduced to the JavaScript language. These allow developers to initialize a function with default values if the arguments are not supplied to the function call. Initializing function parameters in this way will make your functions easier to read and less error-prone, and will provide default behavior for your functions. This will help you avoid errors that stem from passing in undefined arguments and destructuring objects that don’t exist.

ECMAScript 2015中默认功能参数已引入JavaScript语言。 这使开发人员能够初始化函数 ,如果该参数不提供给函数调用默认值。 以这种方式初始化函数参数将使您的函数更易于阅读且不易出错,并且将为函数提供默认行为。 这将帮助您避免由于传入undefined参数以及破坏不存在的对象而引起的错误。

In this article, you will review the difference between parameters and arguments, learn how to use default parameters in functions, see alternate ways to support default parameters, and learn what types of values and expressions can be used as default parameters. You will also run through examples that demonstrate how default parameters work in JavaScript.

在本文中,您将检查参数和参数之间的区别,了解如何在函数中使用默认参数,查看支持默认参数的替代方法,以及了解哪些类型的值和表达式可以用作默认参数。 您还将通过示例演示默认参数在JavaScript中的工作方式。

参数和参数 (Arguments and Parameters)

Before explaining default function parameters, it is important to know what it is that parameters can default to. Because of this, we will first review the difference between arguments and parameters in a function. If you would like to learn more about this distinction, check out our earlier article in the JavaScript series, How to Define Functions in JavaScript.

在解释默认函数参数之前,重要的是要知道参数可以默认为的含义。 因此,我们将首先回顾函数中参数参数之间的差异。 如果您想了解更多关于这种区别的信息,请查阅我们在JavaScript系列文章中的较早文章“ 如何在JavaScript中定义函数”

In the following code block, you will create a function that returns the cube of a given number, defined as x:

在下面的代码块中,您将创建一个函数,该函数返回给定数字的多维数据集,定义为x

// Define a function to cube a number
function cube(x) {
  return x * x * x
}

The x variable in this example is a parameter—a named variable passed into a function. A parameter must always be contained in a variable and must never have a direct value.

在此示例中, x变量是一个参数 —传递给函数的命名变量。 参数必须始终包含在变量中,并且绝对不能具有直接值。

Now take a look at this next code block, which calls the cube function you just created:

现在看一下下一个代码块,它调用刚刚创建的cube函数:

// Invoke cube function
cube(10)

This will give the following output:

这将给出以下输出:


   
   
Output
1000

In this case, 10 is an argument—a value passed to a function when it is invoked. Often the value will be contained in a variable as well, such as in this next example:

在这种情况下, 10是一个参数 —调用时传递给函数的值。 通常,值也将包含在变量中,例如在下一个示例中:

// Assign a number to a variable
const number = 10

// Invoke cube function
cube(number)

This will yield the same result:

这将产生相同的结果:


   
   
Output
1000

If you do not pass an argument to a function that expects one, the function will implicitly use undefined as the value:

如果您不将参数传递给需要一个参数的函数,则该函数将隐式使用undefined作为值:

// Invoke the cube function without passing an argument
cube()

This will return:

这将返回:


   
   
Output
NaN

In this case, cube() is trying to calculate the value of undefined * undefined * undefined, which results in NaN, or “not a number”. For more on this, take a look at the number section of Understanding Data Types in JavaScript.

在这种情况下, cube()尝试计算undefined * undefined * undefined的值,这将导致NaN或“不是数字”。 有关更多信息,请查看理解JavaScript中的数据类型的数字部分。

This automatic behavior can sometimes be a problem. In some cases, you might want the parameter to have a value even if no argument was passed to the function. That’s where the default parameters feature comes in handy, a topic that you will cover in the next section.

这种自动行为有时可能会成为问题。 在某些情况下,即使没有参数传递给函数,您也可能希望参数具有值。 这是默认参数功能派上用场的地方,您将在下一部分中介绍该主题。

默认参数语法 (Default Parameter Syntax)

With the addition of default parameters in ES2015, you can now assign a default value to any parameter, which the function will use instead of undefined when called without an argument. This section will first show you how to do this manually, and then will guide you through setting default parameters.

通过在ES2015中添加默认参数,您现在可以为任何参数分配默认值,该函数将在不带参数的情况下使用该函数代替undefined的函数。 本节将首先向您展示如何手动执行此操作,然后将指导您设置默认参数。

Without default parameters, you would have to explicitly check for undefined values in order to set defaults, as is shown in this example:

如果没有默认参数,则必须显式检查undefined值才能设置默认值,如以下示例所示:

// Check for undefined manually
function cube(x) {
  if (typeof x === 'undefined') {
    x = 5
  }

  return x * x * x
}

cube()

This uses a conditional statement to check if the value has been automatically provided as undefined, then sets the value of x as 5. This will result in the following output:

这使用条件语句来检查是否已将值自动提供为undefined ,然后将x的值设置为5 。 这将导致以下输出:


   
   
Output
125

In contrast, using default parameters accomplishes the same goal in much less code. You can set a default value to the parameter in cube by assigning it with the equality assignment operator (=), as highlighted here:

相反,使用默认参数可以用更少的代码实现相同的目标。 您可以使用等式赋值运算符( = )为cube的参数设置默认值,如下所示:

// Define a cube function with a default value
function cube(x = 5) {
  return x * x * x
}

Now when the cube function is invoked without an argument, it will assign 5 to x and return the calculation instead of NaN:

现在,在不带参数的情况下调用cube函数时,它将为x分配5并返回计算结果,而不是NaN

// Invoke cube function without an argument
cube()

   
   
Output
125

It will still function as intended when an argument is passed, ignoring the default value:

传递参数时,它仍将按预期运行,而忽略默认值:

// Invoke cube function with an argument
cube(2)

   
   
Output
8

However, one important caveat to note is that the default parameter value will also override an explicit undefined passed as an argument to a function, as demonstrated here:

但是,需要注意的一个重要警告是,默认参数值还将覆盖作为函数的参数传递的显式undefined ,如下所示:

// Invoke cube function with undefined
cube(undefined)

This will give the calculation with x equal to 5:

这将使x等于5的计算:


   
   
Output
125

In this case, the default parameter values were calculated, and an explicit undefined value did not override them.

在这种情况下,将计算默认参数值,并且显式的undefined值不会覆盖它们。

Now that you have an idea of the basic syntax of default parameters, the next section will show how default parameters work with different data types.

既然您已经了解了默认参数的基本语法,下一节将说明默认参数如何与不同的数据类型一起使用。

默认参数数据类型 (Default Parameter Data Types)

Any primitive value or object can be used as a default parameter value. In this section, you will see how this flexibility increases the ways in which default parameters can be used.

任何原始值对象都可以用作默认参数值。 在本节中,您将看到这种灵活性如何增加使用默认参数的方式。

First, set parameters using a number, string, boolean, object, array, and null value as a default value. This example will use arrow function syntax:

首先,使用numberstringboolean ,object, array和null值作为默认值来设置参数。 本示例将使用箭头函数语法:

// Create functions with a default value for each data type
const defaultNumber = (number = 42) => console.log(number)
const defaultString = (string = 'Shark') => console.log(string)
const defaultBoolean = (boolean = true) => console.log(boolean)
const defaultObject = (object = { id: 7 }) => console.log(object)
const defaultArray = (array = [1, 2, 3]) => console.log(array)
const defaultNull = (nullValue = null) => console.log(nullValue)

When these functions are invoked without parameters, they will all use the default values:

在不带参数的情况下调用这些函数时,它们都将使用默认值:

// Invoke each function
defaultNumber()
defaultString()
defaultBoolean()
defaultObject()
defaultArray()
defaultNull()

   
   
Output
42 "Shark" true {id: 7} (3) [1, 2, 3] null

Note that any object created in a default parameter will be created every time the function is called. One of the common use cases for default parameters is to use this behavior to obtain values out of an object. If you try to destructure or access a value from an object that doesn’t exist, it will throw an error. However, if the default parameter is an empty object, it will simply give you undefined values instead of throwing an error:

请注意,每次调用该函数时,都会创建使用默认参数创建的任何对象。 默认参数的常见用例之一是使用此行为从对象中获取值。 如果您尝试从不存在的对象中解构或访问一个值,它将引发错误。 但是,如果默认参数是一个空对象,它将仅为您提供undefined值,而不是引发错误:

// Define a settings function with a default object
function settings(options = {}) {
  const { theme, debug } = options

  // Do something with settings
}

This will avoid the error caused by destructuring objects that don’t exist.

这样可以避免因销毁不存在的对象而导致的错误。

Now that you’ve seen how default parameters operate with different data types, the next section will explain how multiple default parameters can work together.

既然您已经了解了默认参数如何在不同的数据类型上运行,下一部分将说明多个默认参数如何一起工作。

使用多个默认参数 (Using Multiple Default Parameters)

You can use as many default parameters as you want in a function. This section will show you how to do this, and how to use it to manipulate the DOM in a real-world example.

您可以在函数中使用任意多个默认参数。 本节将向您展示如何执行此操作,以及如何在实际示例中使用它来操作DOM

First, declare a sum() function with multiple default parameters:

首先,声明具有多个默认参数的sum()函数:

// Define a function to add two values
function sum(a = 1, b = 2) {
  return a + b
}

sum()

This will result in the following default calculation:

这将导致以下默认计算:


   
   
Output
3

Additionally, the value used in a parameter can be used in any subsequent default parameter, from left to right. For example, this createUser function creates a user object userObj as the third parameter, and all the function itself does is return userObj with the first two parameters:

此外,在参数中使用的值可以在从左到右的任何后续默认参数中使用。 例如,此createUser函数创建一个用户对象userObj作为第三个参数,该函数本身所做的只是返回带有前两个参数的userObj

// Define a function to create a user object using parameters
function createUser(name, rank, userObj = { name, rank }) {
  return userObj
}

// Create user
const user = createUser('Jean-Luc Picard', 'Captain')

If you call user here, you will get the following:

如果您在此处致电user ,您将获得以下信息:


   
   
Output
{name: "Jean-Luc Picard", rank: "Captain"}

It is usually recommended to put all default parameters at the end of a list of parameters, so that you can easily leave off optional values. If you use a default parameter first, you will have to explicitly pass undefined to use the default value.

通常建议将所有默认参数放在参数列表的末尾,以便您可以轻松保留可选值。 如果首先使用默认参数,则必须显式传递undefined才能使用默认值。

Here is an example with the default parameter at the beginning of the list:

这是一个默认参数位于列表开头的示例:

// Define a function with a default parameter at the start of the list
function defaultFirst(a = 1, b) {
  return a + b
}

When calling this function, you would have to call defaultFirst() with two arguments:

调用此函数时,必须使用两个参数调用defaultFirst()

defaultFirst(undefined, 2)

This would give the following:

这将给出以下内容:


   
   
Output
3

Here is an example with the default parameter at the end of the list:

这是一个默认参数位于列表末尾的示例:

// Define a function with a default parameter at the end of the list
function defaultLast(a, b = 1) {
  return a + b
}

defaultLast(2)

This would yield the same value:

这将产生相同的值:


   
   
Output
3

Both functions have the same result, but the one with the default value last allows a much cleaner function call.

这两个函数具有相同的结果,但是最后一个具有默认值的函数允许更简洁的函数调用。

For a real-world example, here is a function that will create a DOM element, and add a text label and classes, if they exist.

对于一个实际示例,这里是一个函数,它将创建一个DOM元素,并添加文本标签和类(如果存在)。

// Define function to create an element
function createNewElement(tag, text, classNames = []) {
  const el = document.createElement(tag)
  el.textContent = text

  classNames.forEach(className => {
    el.classList.add(className)
  })

  return el
}

You can call the function with some classes in an array:

您可以使用数组中的某些类来调用该函数:

const greeting = createNewElement('p', 'Hello!', ['greeting', 'active'])

Calling greeting will give the following value:

呼叫greeting将具有以下值:


   
   
Output
<p class="greeting active">Hello!</p>

However, if you leave the classNames array out of the function call, it will still work.

但是,如果将classNames数组保留在函数调用之外,则该数组仍将起作用。

const greeting2 = createNewElement('p', 'Hello!')

greeting2 now has the following value:

greeting2现在具有以下值:


   
   
Output
<p>Hello!</p>

In this example, forEach() can be used on an empty array without an issue. If that empty array were not set in the default parameter, you would get the following error:

在此示例中, forEach()可以毫无问题地用于空数组。 如果未在默认参数中设置该空数组,则会出现以下错误:


   
   
Output
VM2673:5 Uncaught TypeError: Cannot read property 'forEach' of undefined at createNewElement (<anonymous>:5:14) at <anonymous>:12:18

Now that you have seen how multiple default parameters can interact, you can move on to the next section to see how function calls work as default parameters.

既然您已经了解了多个默认参数之间的交互方式,那么可以继续进行下一部分,以了解函数调用如何作为默认参数工作。

函数调用作为默认参数 (Function Calls as Default Parameters)

In addition to primitives and objects, the result of calling a function can be used as a default parameter.

除了基元和对象之外,调用函数的结果还可以用作默认参数。

In this code block, you will create a function to return a random number, and then use the result as the default parameter value in a cube function:

在此代码块中,您将创建一个返回随机数的函数,然后将结果用作cube函数中的默认参数值:

// Define a function to return a random number from 1 to 10
function getRandomNumber() {
  return Math.floor(Math.random() * 10)
}

// Use the random number function as a default parameter for the cube function
function cube(x = getRandomNumber()) {
  return x * x * x
}

Now invoking the cube function without a parameter will have potentially different results every time you call it:

现在,每次不带参数调用cube函数时,可能会产生不同的结果:

// Invoke cube function twice for two potentially different results
cube()
cube()

The output from these function calls will vary:

这些函数调用的输出将有所不同:


   
   
Output
512 64

You can even use built-in methods, like those on the Math object, and use the value returned in one function call as a parameter in another function.

您甚至可以使用内置方法,例如Math对象上的方法,并将一个函数调用中返回的值用作另一个函数的参数。

In the following example, a random number is assigned to x, which is used as the parameter in the cube function you created. The y parameter will then calculate the cube root of the number and check to see if x and y are equal:

在下面的示例中,一个随机数被分配给x ,它用作您创建的cube函数中的参数。 然后, y参数将计算数字的立方根,并检查xy是否相等:

// Assign a random number to x
// Assign the cube root of the result of the cube function and x to y
function doesXEqualY(x = getRandomNumber(), y = Math.cbrt(cube(x))) {
  return x === y
}

doesXEqualY()

This will give the following:

这将给出以下内容:


   
   
Output
true

A default parameter can even be a function definition, as seen in this example, which defines a parameter as the inner function and returns the function call of parameter:

如本示例所示,默认参数甚至可以是函数定义,该定义将参数定义为inner函数并返回parameter的函数调用:

// Define a function with a default parameter that is an anonymous function
function outer(
  parameter = function inner() {
    return 100
  }
) {
  return parameter()
}

// Invoke outer function
outer()

   
   
Output
100

This inner function will be created from scratch every time the outer function is invoked.

每次调用outer函数时,都会从头开始创建此inner函数。

结论 (Conclusion)

In this article, you learned what default function parameters are and how to use them. Now you can use default parameters to help keep your functions clean and easy to read. You can also assign empty objects and arrays to parameters upfront to reduce both complexity and lines of code when dealing with situations such as retrieving values from an object or looping through an array.

在本文中,您了解了什么是默认函数参数以及如何使用它们。 现在,您可以使用默认参数来帮助保持功能的整洁和易于阅读。 您还可以预先将空对象和数组分配给参数,以减少处理诸如从对象中检索值或遍历数组等情况时的复杂度和代码行数。

If you would like to learn more about JavaScript, check out the homepage for our How To Code in JavaScript series, or browse our How to Code in Node.js series for articles on back-end development.

如果您想了解有关JavaScript的更多信息,请查看我们的“ 如何在JavaScript中进行编码”系列的主页,或浏览我们的“ 如何在Node.js中进行编码”系列以获取有关后端开发的文章。

翻译自: https://www.digitalocean.com/community/tutorials/understanding-default-parameters-in-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: JavaScript 的函数可以理解为一个独立的代码块,它可以接收输入(参数),并返回输出(返回值)。函数是一种重用代码的方法,您可以定义一个函数,并在需要时多次调用它。它有助于提高代码的可读性和可维护性,并使您可以将代码块分组,以便更好地管理和维护代码。 举个例子,您可以定义一个计算两个数字之和的函数,并在需要计算和的任何地方调用该函数。这有助于减少重复代码,并且您可以在函数内部修改代码,而不会影响调用该函数的其他地方。 总之,理解 JavaScript 的函数需要一些实践和练习。在继续学习之前,您需要对代码块、参数和返回值有一个基本的了解,然后再深入了解函数的用法。 ### 回答2: JavaScript的函数是一种具有重复利用性的代码块。它们允许我们将一系列逻辑操作封装在一个单独的单元,并且可以在需要的时候多次调用。 函数的定义使用`function`关键字,后面跟着函数名和一对括号,括号可以包含函数的参数。函数的主体部分被包裹在大括号,里面可以包含任意数量的语句,这些语句组成了函数的逻辑。 函数的定义通常在代码的前面或者其他函数的内部。为了调用函数,我们需要使用函数名和一对括号来执行函数。如果函数定义包含参数,则需要在括号传递对应的参数值。 函数可以返回一个值,我们可以使用`return`关键字来指定函数的返回值。当函数执行到`return`语句时,函数将停止执行,并将返回值传递回调用者。 函数可以被当作变量一样进行赋值,也可以作为其他函数的参数或者返回值。这使得函数能够更灵活地应用在各种场景。 理解JavaScript函数的关键是理解它们的作用和如何使用。函数使我们可以将复杂的代码分解为可管理的模块,并且提供了代码重用的机制。它们也具有作用域的概念,函数内部的变量仅在函数内部可见,这有助于保持代码的整洁和可维护性。 总之,JavaScript的函数是一种灵活且重要的代码结构,我们可以通过定义、调用和传递函数来实现逻辑的封装、重用和组合。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值