Two Sums JS (forEach)



我一直在试图弄清楚为什么我的代码不工作。

const twoSum = function (arr, target) {
const newMap = new Map();
const newArr = arr.forEach(function (num, i, arr) {
if (newMap.has(target - num)) return [newMap.get(target - num), i];
else newMap.set(num, i);
console.log(newMap);
});
return [];
};
console.log(twoSum([3, 1, 3, 4, 5, 1, 2, 3], 9));

您在回调函数中使用return而不是在主函数(twoSum())中,因此towSum函数只有一个返回[],以避免您可以像在twoSum1()示例中那样使用for循环,但如果您坚持使用.forEach方法,基于此答案,您可以使用另一个collback函数来接收返回,如twoSum2()示例

const twoSum1 = function (nums, target) {
const newMap = new Map();
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (newMap.has(target - num)) {
return [newMap.get(target - num), i];
}
newMap.set(num, i);
}
};
console.log("from the first method: ");
console.log(twoSum1([3, 1, 3, 4, 5, 1, 2, 3], 9));
const twoSum2 = function (arr, target, fn) {
const newMap = new Map();
const newArr = arr.forEach(function (num, i) {
if (newMap.has(target - num)) fn([newMap.get(target - num), i]);
else newMap.set(num, i);
});
return newArr;
};
twoSum2([3, 1, 3, 4, 5, 1, 2, 3], 9, (result) => {
console.log("from the second method: ");
console.log(result);
});

最新更新