我在一个编程游戏的修正中看到了这行代码
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/