首页 > 解决方案 > 你能帮我理解代码吗?任务是找到第一个非连续数字

问题描述

const firstNonConsecutive = arr => arr.find((number, index) => index > 1 && number !== arr[index -1] + 1)

有没有人可以帮我分解上述功能?我写了一个很长的代码来解决这个任务,有人给我发了一个更正,说我的代码可以简化。

标签: javascriptarraysnumbersfindsimplification

解决方案


我要做的第一件事是添加花括号并将其分解为多行:

// This function takes an Array
const firstNonConsecutive = arr => {
  // And tries to find an item
  return arr.find((number, index) => {
    return index > 1 && // Starting from index 2 (the first 2 are ignored)
      number !== arr[index - 1] + 1; // Where the value is not (previous value + 1)
  });
}

console.log(firstNonConsecutive([128, 6, 2, 8])); // 2         -> ??
console.log(firstNonConsecutive([5, 6, 2, 8]));   // 2         -> correct
console.log(firstNonConsecutive([5, 6, 7, 8]));   // undefined -> correct

然后,如果您不知道该方法,您可以在Array.prototype.find(). 它需要一个回调函数,它将在每个项目上执行,直到该回调在某个时候返回true (或任何真实值) 。如果是,它将返回该值。否则,如果没有符合条件的项目,它将返回undefined

这应该足以理解它的作用?

奇怪的是它从索引 2 ( 开始index > 1)。使用这个逻辑,这意味着第一个项目永远不会被检查。也许这个条件应该是index > 0

// This function takes an Array
const firstNonConsecutive = arr => {
  // And tries to find an item
  return arr.find((number, index) => {
    return index > 0 && // Starting from index 1 (the first is ignored)
      number !== arr[index - 1] + 1; // Where the value is not (previous value + 1)
  });
}

console.log(firstNonConsecutive([128, 6, 2, 8])); // 6         -> correct
console.log(firstNonConsecutive([5, 6, 2, 8]));   // 2         -> correct
console.log(firstNonConsecutive([5, 6, 7, 8]));   // undefined -> correct

这是一种更解构的写法:

function firstNonConsecutive(arr) {
  // Find an item that passes the condition
  return arr.find(passesCondition);
  
  function passesCondition(number, index) {
    return index > 0 && number !== arr[index - 1] + 1;
  }
}

console.log(firstNonConsecutive([128, 6, 2, 8])); // 6         -> correct
console.log(firstNonConsecutive([5, 6, 2, 8]));   // 2         -> correct
console.log(firstNonConsecutive([5, 6, 7, 8]));   // undefined -> correct


推荐阅读