问题
用js刷leetcode第1题,forEach和for循环执行,返回结果为什么不一样,如下图代码
for循环
返回[0,1]
var nums = [2, 7, 11, 15], target = 9;
var twoSum = function (nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
var n1 = nums[i]
var n2 = target - n1;
if (map.has(n2)) {
return [map.get(n2), i]
} else {
map.set(n1, i)
}
}
};
var result = twoSum(nums, target)
console.log('result', result)
forEach
返回 undefined
var nums = [2, 7, 11, 15], target = 9;
var twoSum = function (nums, target) {
const map = new Map()
nums.forEach((item, index) => {
let n1 = nums[index];
let n2 = target - n1
if (map.has(n2)) {
return [map.get(n2), index]
} else {
map.set(n1, index)
}
})
};
var result = twoSum(nums, target)
console.log('result', result)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…