For 和 Foreach 循环以及 return with Set。数组中的第一个循环数字

For and Foreach loop and return with Set. First recurring number in array

我的问题是关于 return 这些循环的结果。这是我的代码。 函数应该接受数组作为输入,并且 return 是其中的第一个循环数字。我决定在这里使用 Set 对象。

const arr1 = [2, 2, 3, 2, 5, 6, 6, 9]; 

  const recurring = (arr) => {

    const set = new Set();

    // This returns undefined
    arr.forEach(el => {
      if (set.has(el)) {
        return el;
      } else {
        set.add(el); 
      }   
    })       

    // This returns 2
    for (let el in arr) {
     if (set.has(arr[el])) {
       return arr[el];
     } else {
       set.add(arr[el]); 
     }   
    } 

  }

    recurring(arr1); // Should return 2

在使用 forEach 循环的第一种情况下,一切正常,我可以 console.log Set 和 el 并且我可以看到它,但是由于某种原因它 return 未定义。

在第二种情况下,使用 for in 循环一切正常,但实际上 return 是值。

在 return 关键字的情况下,这些循环之间有很大的区别吗? 我错过了什么?

在使用 forEach 的情况下,您传递的是匿名函数。在该范围内,return 将退出 forEach 函数,您的包装函数 recurring 将继续执行以下代码。

在第二个示例中,您没有创建另一个函数,因此 return 适用于 recurring 函数。

您需要 return 函数中的某些内容,并且您需要使用 find 而不是 forEach,因为最后一个不考虑任何 return 值。

const arr1 = [2, 2, 3, 2, 5, 6, 6, 9];

const recurring = (arr) => {
    const set = new Set();
    return arr.find(el => {
        if (set.has(el)) return true;
        set.add(el);
    });
};

console.log(recurring(arr1));

事实上 .forEach() method 的问题是它的 callback 函数总是 return undefined,即使你使用return 语句。

如果您检查 forEach() method MDN reference,您会看到:

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

所以在你的情况下 return el; 里面的 forEach() 回调总是被忽略,而 forEach 回调里面 return 是特定于这个范围的,这就是为什么 function 不会 return 什么。

解法:

如果你想用 forEach() 来做,你可以做的是将这个 flag 存储在一个变量中,这样你就可以 return 它在 forEach() 之后块:

const recurring = (arr) => {

  const set = new Set();
  let result;
  arr.forEach(el => {
    if (set.has(el)) {
       result = !result ? el : result;
      return;
    } else {
      set.add(el);
    }
  });
  return result;
}

演示:

const arr1 = [2, 2, 3, 2, 5, 6, 6, 9];

const recurring = (arr) => {

  const set = new Set();
  let result;

  arr.forEach(el => {
    if (set.has(el)) {
      result = !result ? el : result;
      return;
    } else {
      set.add(el);
    }
  });
  return result;
}

console.log(recurring(arr1));

另一种方法,保持简单:

const recurring = (arr) => {
    for(let r = 0; r < arr.length; r++){
        if(arr.indexOf(arr[r],r+1)>-1)return arr[r];
    }
}