每个参数之间的MDN javascript语法文档中的括号是什么意思?

Red*_*edA 0 javascript syntax

我不明白MDN javascript语法文档中所有这些括号的含义。

例如, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

在本文档中,逗号“,”前的每个参数之间都有括号“ [”

Array.prototype.map()

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])
Run Code Online (Sandbox Code Playgroud)

但是当我实际编写代码时,

var numbers = [1, 4, 9];
var info = numbers.map(function(num,index) { 
    return "index: " + index + ", number: " + num;
});

console.log(info)

//output:   ["index: 0, number: 1", "index: 1, number: 4", "index: 2, number: 9"]
Run Code Online (Sandbox Code Playgroud)

我不使用数组或在参数中放入[...这些括号在文档中是什么意思?

在此处输入图片说明

Lud*_*dla 5

这些括号表示可选参数。这意味着,您不必包括那些参数。

例如:可以说我有递增函数:inc(x)需要一个参数。调用时,它将使该变量精确地加一。inc(x)等于x++ 但是我也希望可以选择增加任何数字。例如:inx(x, 3)其结果与相同x = x + 3。然后,我可以像在MDN上一样描述我的功能:

function inc(variable [,increment])
Run Code Online (Sandbox Code Playgroud)

  • @Ok - 这意味着,仅当使用可选参数 _index_ 时,_array_ 参数才可以是可选的。您可以使用 `callback(accumulator, currentValue, index)` 或 `callback(accumulator, currentValue, index, array)` 但不能使用 `callback(accumulator, currentValue, array)` 因为 _array_ 参数仅在使用 _index_ 时才起作用 (2认同)