简体   繁体   中英

Javascript - return value from a loop

function findOdd(A) {
  var odd = 0;
  A.forEach(num => {
    A.forEach(num2 => {
      if (num == num2) {
        odd = odd + 1;
      };
    });

    if (odd % 2 == 1) {
      console.log("num = " + num);
      return num;
    }
    odd = 0;
  });
}

var result = findOdd([5, 0, 0, 0, 2, 2, 3, 3, 4, 4]);

console.log(result);

When I try to return num, it is returning as undefined. And if I remove the "return" statement it is printing correctly to the console.

You can't break out of forEach using return and return it. You are not returning anything from your function as return from foreach does not get returned.

You can use for loop to do this.

 function findOdd(A) { var odd = 0; for (let i = 0; i < A.length; i++) { for (let j = 0; j < A.length; j++) { if (A[i] == A[j]) { odd = odd + 1; } } if (odd % 2 == 1) { console.log("num = " + A[i]); return A[i]; } odd = 0; } } var result = findOdd([5, 0, 0, 0, 2, 2, 3, 3, 4, 4]); console.log(result);

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