javascript - 使用 Math.max 调用 Array.prototype.map 返回 NaN 数组

标签 javascript arrays

<分区>

为什么 [1, 2, 3].map((x) => Math.max(x)) 返回 [1, 2, 3]

然而 [1, 2, 3].map(Math.max) 返回 [NaN, NaN, NaN]

我本来以为 [1, 2, 3].map(Number) 返回 [1, 2, 3],同样适用于使用 Math.max 同理。

特别是因为 Math.max(3) == Number(3)

最佳答案

是因为map使用三个参数调用回调:

  1. 当前数组元素。
  2. 当前元素的索引。
  3. 数组 map 被调用。

所以 [1, 2, 3].map(Math.max) 不等同于 [1, 2, 3].map((x) => Math.max (x)),但到 [1, 2, 3].map((x, i, arr) => Math.max(x, i, arr)).

Math.max(1, 0, [1, 2, 3])NaN 因为 [1, 2, 3] 数组在字符串化时变为 "1,2,3",在转换为数字时变为 NaN

关于javascript - 使用 Math.max 调用 Array.prototype.map 返回 NaN 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52664121/

相关文章:

javascript - Swiper.IO 分页点现在显示

php - 将多维数组循环到mysql中

c++ - 多维数组逻辑

arrays - 数组返回 null 并崩溃

javascript - 使绝对定位的 div 下方的元素可点击

javascript - 修复 header 偏移 html anchor

javascript - 从对象树构造平面数组

python - 三维数组作为向量和矩阵的乘法

javascript - 如何在事件处理程序上运行 jquery 脚本

javascript - jQuery 问题 : Running a function through each and picking up the element