return语句在javascript try块中不起作用

时间:2019-01-27 12:48:28

标签: javascript return try-catch

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();

1 个答案:

答案 0 :(得分:1)

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());