javascript - 我想使用不同的语法以方便调试。为什么它不起作用?
问题描述
这是我无法解决的问题,它来自codingGame。我看到了一个解决方案,但我尝试使用不同的语法以便更好地理解。
语境
/** Horse Racing Duals (easy) https://www.codingame.com/training/easy/horse-racing-duals
* This puzzle shows that sometimes, the simplest solution is not performant
* enough. You will also learn to handle large arrays and gain experience
* with their processing time.
*
* STATEMENT:
* In this problem you have to find the two numbers that are closest to each
* other among a list of numbers. The list might be really large and force
* you to search for the best possible algorithmic complexity for your
* solution.
*
* STORY:
* To make a race between two horses interesting, you will have to find the
* horses with the closest strength.
**/
print(
new Array(+readline())
.fill()
.map(() => +readline())
.sort((a, b) => a > b)
.map((x, i, arr) => Math.abs(x - arr[i + 1]))
.sort((a, b) => a > b) [0]
);
为什么我不能这样做:
let tab = new Array(+readline())
tab.fill()
tab.map(() => +readline())
tab.sort((a, b) => a > b)
tab.map((x, i, arr) => Math.abs(x - arr[i + 1]))
tab
解决方案
为什么我不能这样做:
因为有些map
方法返回一个带有更改的新数组,而不是就地进行更改。
在您的示例中,仅就sort
地改变数组,因此您的代码实际上等同于:
let tab = new Array(+readline())
tab.sort((a, b) => a > b)
请注意,sort
回调应该返回一个正数、负数或0
. 它不应该返回 Boolean。
推荐阅读
- rabbitmq - 集群上节点的 RabbitMQ 问题
- php - PHP从单个stdClass对象数组中的关联数组中获取/检查值
- javascript - 防止 insertBefore 复制内容
- angular - Get 方法来不及从服务器拉取数据
- glassfish-4.1 - JavaMelody 错误 - 在 GlassFish v4.1 中监控 sql 请求和 jdbc 连接
- android - EditText 的提示不适用于 Android 4.0.4 中的阿拉伯语
- angular - 监视可观察的内部方法
- quarkus - 如何禁用 Quarkus 对文件 (quarkus.log) 的日志记录?
- python - 从子包导入python3模块
- python - 使用OpenCV从二值图像中提取矩形