javascript - 我想知道这个函数到底做了什么 .split (' ' ).map(x => +x);

标签 javascript dictionary arrow-functions

我在一个编程游戏的修正中看到了这行代码

const tC = readline().split(' ').map(x => +x);

我想知道它做了什么,因为当我记录这个函数时,它呈现与这个函数相同的东西

const tC = readline().split(' ').map(x => x);

但其余的代码不起作用

上下文:

/** Temperatures (easy) https://www.codingame.com/training/easy/temperatures
 * Solving this puzzle validates that the loop concept is understood and that
 * you can compare a list of values.
 * This puzzle is also a playground to experiment the concept of lambdas in
 * different programming languages. It's also an opportunity to discover
 * functional programming.
 *
 * Statement:
 * Your program must analyze records of temperatures to find the closest to
 * zero.
 *
 * Story:
 * It's freezing cold out there! Will you be able to find the temperature
 * closest to zero in a set of temperatures readings?
**/
const N = +readline();
const tC = readline().split(' ').map(x => +x);

let min = Infinity;

for (let i in tC) {
    (Math.abs(tC[i]) < Math.abs(min) || tC[i] === -min && tC[i] > 0) && (min = tC[i]);
}

print(min || 0);

非常感谢

最佳答案

.map(x => +x) 将数组中的所有项目转换为数字。并返回一个包含这些转换值的新数组。

如果您将其更改为 .map(x => x),那么这些值将保持不变,您只需创建原始数组的副本。所以字符串仍然是字符串,如果需要数字,这些字符串将破坏代码。

我个人会避免使用 +x 语法并使用更冗长的 Number(x),并编写 .map(x => Number(x )).map(Number).

关于javascript - 我想知道这个函数到底做了什么 .split (' ' ).map(x => +x);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52702610/

相关文章:

javascript - 为什么 D3 过渡不起作用

javascript 函数搜索覆盖像素的所有 OpenLayers 矢量特征

javascript - if条件不满足时数组中返回空值和逗号,JS映射箭头函数

php - 在箭头函数中通过引用使用变量

javascript - "$injector:modulerr": throwing error for module name is not available but actually it is available

javascript - AngularJS 的 While 循环?

java - 生成值和键来填充 map ,以及我应该使用哪种类型的 map

Python:如何在不反转原始字典的情况下反转新字典中的列表

python - 访问嵌套字典 panda 中的单元格的最佳方式是什么?

reactjs - 为什么React中我们不需要绑定(bind)箭头函数?