首页 > 解决方案 > 我总是想知道类似 [, thisArg] 的东西的含义

问题描述

有时我在MDN研究Javascript代码,但我不明白[,thisArg]的东西是什么意思......例如,

arr.map(callback(currentValue[, index[, array]])[, thisArg])

在这种情况下,我知道需要有回调函数。但方括号中的内容是什么?如果前面没有任何内容,为什么他们需要逗号?

标签: javascript

解决方案


这意味着括号中的任何内容都是可选参数。如果确实使用了附加的可选参数,则需要用逗号将其与前一个参数隔开。

符号

arr.map(callback(currentValue[, index[, array]])[, thisArg])

也许更容易理解为

arr.map(
  callback(currentValue[, index[, array]])
  [, thisArg]
)

表示回调可以接受 1、2 或 3 个参数,并且.map接受回调作为第一个参数,并且还可以选择接受第二个参数 (the thisArg)。

正如 Kaiido 所指出的,在 的特定情况下Array.prototype.mapcurrentValue实际上也是可选的,在.map不使用任何参数的情况下使用它是非常奇怪的:

const arr = [3, 4];
const newArr = arr.map(() => 999);
console.log(newArr);


推荐阅读