【发布时间】:2022-01-15 07:47:06
【问题描述】:
我用这段代码返回 null,但是我看不出为什么/哪里出错了。 (这可能是由于排序功能,因为我从一个备受好评的 sn-p 关于如何对数组进行排序得到了这个)。比起正确答案,我更在乎理解。
我想要完成的任务:
Ratiorg 从 CodeMaster 那里得到了不同尺寸的雕像作为生日礼物,每个雕像都有一个非负整数大小。因为他喜欢把事情做得完美,所以他想把它们从小到大排列,这样每个雕像都会比前一个大一倍。他可能需要一些额外的雕像才能做到这一点。帮助他找出所需的最少额外雕像数量。
例子
对于
statues = [6, 2, 3, 8],输出应该是solution(statues) = 3.Ratiorg 需要尺寸为 4、5 和 7 的雕像。
我的代码和想法:
function solution(statues) {
let total = 0;
statues.sort(function(a, b) { //From what I understand this should sort the array numerically
return a - b;
});
for (let i = 1; i < statues.length; i++) { //iterate through the array comparing the index to the one before it
if (statues[i + 1] != (statues[i] + 1)) { //if there is a diff between index of more than 1 it will add the diff
total += statues[i + 1] - statues[i]; //to the total variable
}
}
return total;
}
const result = solution([6, 2, 3, 8]);
console.log(result);
【问题讨论】:
-
当
i == statues.length - 1statues[i + 1]返回undefined,然后将其添加到total得到结果NaN。 -
为什么忽略第一个元素(
let i = 1;)? -
为什么说它返回的是
null,而实际上它返回的是NaN? -
既然你是从
1开始的,我想你应该和statues[i-1]比较,而不是statues[i+1]。
标签: javascript null