This question already has answers here:
Short circuit Array.forEach like calling break
                            
                                (32个答案)
                            
                    
                去年关闭。
        

    

return语句通常终止函数执行。但是我已经意识到return语句不能像我期望的那样工作?问题出在哪里?

function SimpleSymbols() {
    ["a", "b", "c", "d"].forEach(function (char, index) {
        try {
            console.log("alert");
            return "false";  //this line does not work?
        } catch (err) {

        }
    });
}

SimpleSymbols();

最佳答案

forEach()不返回。循环完成后,您可以从循环外部返回:



function SimpleSymbols() {
  var r;
  ["a", "b", "c", "d"].forEach(function (char, index) {
    try {
        console.log("alert");
        r = "false";  //this line does not work?
    } catch (err) {
    }
  });
  return r
}

console.log(SimpleSymbols());





相反,您可以使用普通的for循环:



function SimpleSymbols() {
  var arr = ["a", "b", "c", "d"]
  for(var i=0; i<arr.length; i++){
    try {
        console.log("alert");
        return "false";  //this line does not work?
    } catch (err) {
    }
  }
}

console.log(SimpleSymbols());

09-28 05:53