Here is my code to solve leetcode- Two sum
let nums = [2, 7, 11, 15];
let target = 9;
for (let i = 0; i < nums.length; i++) {
let x = target - nums[i];
if (nums[i + 1] === x) {
console.log([i, i+1]) // [0, 1]
return [i, i + 1];
}
} //it ok
nums.forEach((item, index) => {
let x = target - nums[index];
if (nums[index + 1] === x) {
console.log([index, index + 1]);// [0, 1]
return [index,index+1]
}
}); // undefined
I use forEach
instead of for(...)
, both console.log are same, but forEach
returns undefined
. Why?
You can use JS map because the forEach always return undefined
let nums = [2, 7, 11, 15],
target = 9;
let m = {};
nums.map((value, index) => {
m[value] = index;
});
for (i = 0; i < nums.length; i++) {
let diff = target - nums[i];
if (m.hasOwnProperty(diff)) {
console.log(i, m[diff]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.