javascript - 你能帮我理解代码吗?任务是找到第一个非连续数字
问题描述
const firstNonConsecutive = arr => arr.find((number, index) => index > 1 && number !== arr[index -1] + 1)
有没有人可以帮我分解上述功能?我写了一个很长的代码来解决这个任务,有人给我发了一个更正,说我的代码可以简化。
解决方案
我要做的第一件事是添加花括号并将其分解为多行:
// 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
推荐阅读
- javascript - 如何为 TypeScript 项目的不同部分配置不同的 ES 目标?
- amazon-web-services - AWS 应用程序负载均衡器目标组日志
- web - 使用 C# 向策略服务器提交 Web 证书请求
- mysql - 获取拥有超过 2 个文档但没有类型 2 的所有联系人
- c - 如何在 mate-screensaver 中显示和隐藏“板载”屏幕键盘?
- php - PHP ImageClassifier 是用图像训练的,当测试再次对其进行分类时,我得到了相反的结果?
- typescript - 打字稿中的意外类型“从不”
- prometheus - 如何在 Prometheus 警报中匹配多个标签?
- java - 升级 Jackson-databind 后,缺少的字段将反序列化为 null 而不是空对象
- sql - 验证选择正则表达式中的序号和字符