所以我有一个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;
});
答案 0 :(得分:4)
您可以使用
throw "Item does not exist!"
但是我发现最好抛出一个Error
对象,如下所示:
throw new Error("Item does not exist!");
如果你抛出一个Error
,你可以获得更好的可追溯性。令人遗憾的是,JavaScript中的错误处理仍然很糟糕。
答案 1 :(得分: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";
}
答案 2 :(得分: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");
}