简体   繁体   中英

why JavaScript function returns undefined?

TwoSum, needs to return indices of the integers that add up to the target: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].

I'm new to JavaScript and I dont understand why this returns undefined. After a few tests, i noticed it doesn't even enter the 2nd forloop, however when i wrote this in python it works perfectly

 var twoSum = function(nums, target) { for (let i = 0; i < nums.length; i++) { if (nums[i] >= target) { continue; } for (let j = i; j < nums.legth; j++) { if (nums[j] >= target) { continue; } if (nums[i] + nums[j] === target) { const ans = [i, j] return ans; } } } }; console.log(twoSum([2,7,11,15],9));

any help would be appreciated

You made a typo mistake. Fix legth to length in second loop.

 var twoSum = function (nums, target) { for (let i = 0; i < nums.length; i++) { if (nums[i] >= target) { continue; } for (let j = i; j < nums.length; j++) { if (nums[j] >= target) { continue; } if (nums[i] + nums[j] === target) { const ans = [i, j]; return ans; } } } }; console.log(twoSum([2, 7, 11, 15], 9));

I see this is an old question but still...

You have nested loops and that can be very confusing. One way I'd advise you to explore is to have your var ans defined in the function's main scope because you're not returning anything otherwise;

But I'd much rather advise you to use Array.reduce() as is current practice. Here is my solution in leetcode :

 var twoSum = function(nums, target) { let acc = nums.reduce((acc, curr, currIndex, array) => { array.forEach((number, index) => { if(number + curr === target && index !== currIndex) { acc = [currIndex, index]; } }) return acc; }, []); return acc.sort(); };

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM