数组中找出两项相加后的和为num的索引位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function fn(num = 0, ary = []) {
for (let i = 0; i < ary.length; i++) {
let diff = num - ary[i];
let diffIndex = ary.indexOf(diff);
if (diffIndex !== -1 && diffIndex !== i) {
return [i, diffIndex];
}
}
return false;
}

let num = 3;
let arr = [-1, 4, 6, 2];

console.log(fn(num, arr)); // [0, 1]