Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

用js刷leetcode第1题,forEach和for循环执行,返回结果为什么不一样,如下图代码

问题

用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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

看return语句所在。
forEach的参数是个函数,return语句相当于结束这个函数的运行,并不是外层函数。外层函数相当于没有return语句,默认返回undefined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...