方括号前面的逗号 - MDN文档

MDN是我的主要脚本资源。我经常看到这样的符号:( currentValue[, index[, array]])


let new_array = arr.map(function callback( currentValue[, index[, array]]) {

    // return element for new_array

}[, thisArg])

我很惊讶逗号前面有一个方括号。对我来说,它看起来像一个无效的语法。


如果有人能提供有关此符号的更多信息,我将不胜感激。


长风秋雁
浏览 93回答 3
3回答

杨魅力

方括号表示封闭的参数是可选的。有关详细信息,请参阅 MDN 语法部分。

互换的青春

这意味着回调需要 currentValue 作为第一个参数,索引和数组是可选参数。

尚方宝剑之说

它是无效的 JS 语法,并且会引发错误。但是,它用于将可选参数表示为伪代码。方括号中的部分被认为是可选的(在实际代码中,括号应该省略),所以,你可以这样调用这个函数:let new_array = arr.map(function callback(currentValue) {    // return element for new_array})//orlet new_array = arr.map(function callback(currentValue) {    // return element for new_array}, thisArg)//orlet new_array = arr.map(function callback(currentValue, index) {    // return element for new_array})//orlet new_array = arr.map(function callback(currentValue, index) {    // return element for new_array}, thisArg)//orlet new_array = arr.map(function callback(currentValue, index, array) {    // return element for new_array})//orlet new_array = arr.map(function callback(currentValue, index, array) {    // return element for new_array}, thisArg)它们中的每一个都是有效的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript