js 数组中寻找两个值相加等于目标值, 三个值相加等于目标值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> <script type="text/javascript"> let nums = [1, 5, 2, 4, 6, 8]; let target = 12; function twoNum (nums, target){ let arr = []; for(let i = 0;i < nums.length;i++){ let otherNum = target - nums[i]; let secondNum = nums.slice(i+1).filter(val => val == otherNum); if(secondNum.length > 0){ arr.push(i, nums.indexOf(secondNum[0])); } } return arr; } function three(nums, target){ let resultArr = []; for(let i = 0;i < nums.length;i++){ let otherNum = target - nums[i]; let arr = twoNum(nums.slice(i+1), otherNum); if(arr.length > 0){ resultArr.push(i, nums.indexOf(nums.slice(i+1)[arr[0]]), nums.indexOf(nums.slice(i+1)[arr[1]])); break; } } return resultArr } three([1, 4, 8, 12, 19, 16, 26], 24); </script> </html>