【问题标题】:trying to get a quantity of absent elements in the array [duplicate]试图在数组中获取一定数量的缺失元素[重复]
【发布时间】:2018-03-08 01:07:50
【问题描述】:

我正在尝试处理具有非连续数字的数组。这是我的例子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... 有什么问题?

【问题讨论】:

  • 试试Math.max(...myArray)Math.min(...myArray)Math.minMath.max 需要逗号分隔的数字列表,而不是数组。您可以使用spread operator (...) 将数组表示为参数列表。在标记的副本中有一个进一步说明的答案。
  • function makeArrayConsecutive(myArray) { maxVal = myArray.reduce(function(a,b){ return Math.max(a,b)}) minVal = myArray.reduce(function(a,b){ return Math.min(a,b)}) return maxVal-minVal+1-myArray.length }

标签: javascript


【解决方案1】:

这是我认为适合您的一种解决方案:

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));

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2011-07-30
    • 2021-12-12
    • 1970-01-01
    • 2012-03-27
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多