我正在尝试处理具有非连续数字的数组。这是我的示例var myArray = [2, 4, 6, 8]
。缺席的数字是3, 5, 7 and the quantity = 3
。我试着用这个函数`
function makeArrayConsecutive(myArray) {
return Math.max(myArray) - Math.min(myArray) + 1 - myArray.length;
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));

这必须返回3 ...但是它返回NaN ...问题是什么?
答案 0 :(得分:0)
以下是我认为适合您的一个解决方案:
function makeArrayConsecutive(arr) {
//get the min and max using reduce
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});
//amount of numbers b/t min/max if array had no "gaps"
var deltaDesired = ((max - min) - 1);
//actual amount of numbers b/t min/max in our array
var deltaActual = (arr.length - 2);
return (deltaDesired - deltaActual);
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));