2

所以我有一个 if 语句,我想要它,这样如果条件为真,就会抛出一个错误。这是一种供用户从名为 myArr 的数组中删除项目的表单,如果该项目在 myArr 中不存在,我希望它引发错误。

$('#remove_user').submit(function(){
    id = $('#user_num').val();
    diffVal = $.grep(myArr, function(value, i){
        return value != id;
    });
    if (diffVal.length == myArr.length) {
        //I want the error here to say "Does not exist."
    } else {
        myArr = diffVal
    };
    $('#user_list').html('');
    for (var i=0; i < myArr.length; i += 1) {
        $('#user_list').append('<li>' +myArr[i]+ '</li>');
    };
    return false;
});
4

3 回答 3

4

您可以使用

throw "Item does not exist!"

但我发现最好扔一个Error物体,像这样:

throw new Error("Item does not exist!");

如果你抛出一个,Error你会得到更好的可追踪性。遗憾的是,JavaScript 中的错误处理仍然很糟糕。

于 2012-08-20T19:17:34.453 回答
1

我个人最喜欢的是在抛出错误时也使用跟踪

if (diffVal.length == myArr.length) {
    //I want the error here to say "Does not exist."
    Console.log("Error: Does not exist");
    Console.trace();
    throw new Error("Item does not exist");
}
于 2012-08-20T19:20:06.170 回答
1

只需使用throw

if (diffVal.length == myArr.length) {
    //I want the error here to say "Does not exist."
    throw "Item does not exist in the array";
}    
于 2012-08-20T19:17:19.553 回答