【问题标题】:Try/catch block not working as expected with array of variablesTry/catch 块无法按预期使用变量数组
【发布时间】:2015-03-26 13:00:39
【问题描述】:

我有一个使用 3 个变量和一个 try catch 的函数。我想将这 3 个变量用作数组的一部分,但如果我这样做了,我将无法正确完成 try catch 和函数

JS:

function calculateVolume() {

    length = document.getElementById("Length").value;
    width = document.getElementById("Width").value;
    height = document.getElementById("Height").value;
    try {
        if ((length > 1000) || (width > 1000) || (height > 1000))
            throw "err"
        else
            var volume = length * width * height;
        alert(volume);
    } catch (err) {
        alert("You have not entered all three dimensions correctly");
    }
}

【问题讨论】:

  • 你遇到了什么错误?
  • 您的代码运行良好。究竟是什么问题?
  • 请注意:虽然可以在 js 中将任何你想要的东西作为错误抛出,但你仍然应该使用真正的 Error 对象。您可能想阅读answer 到问题Throwing strings instead of Errors
  • @tymeJV 可能你不知道,但在 js 中 var_hoisting
  • 数组在哪里出现 - 我没有看到它?长度、宽度和高度是否意味着在一个数组中?

标签: javascript arrays variables try-catch


【解决方案1】:

如果我没看错你的问题,你希望 lengthwidthheight 在一个数组中,并且你希望条件检查它们的相关值。

您可以使用some,如:

arr.some(function (el) { return el > 1000; });

这个会抛出错误的例子:

var a = 1000,
    b = 1000,
    c = 2000;

var arr = [a, b, c];

try {
    if (arr.some(function (el) { return el > 1000; })) {
        throw "err"
    } else {
        console.log('no error')
    }
} catch (err) {
    console.log("You have not entered all three dimensions correctly");
}

DEMO

【讨论】:

    猜你喜欢
    • 2016-01-23
    • 2019-05-26
    • 1970-01-01
    • 2014-08-09
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多