0

为什么会这样编译:

this.setAlunos = function(alunos){
    if(this.getTurma() > 0){
        this.alunos = alunos.split(",");
    }
    else{
        throw "you must set a 'turma' before inserting students on it";
    }
};

这不是吗?

this.setAlunos = function(alunos){
    this.getTurma() > 0 ? this.alunos = alunos.split(",") : throw "you must set a 'turma' before inserting students on it";
};
4

1 回答 1

2

你实际上不能直接在三元运算符中抛出错误,就像你试图在那里做的那样。但是,您可以将 包装throw在匿名函数中,如下所示:

this.setAlunos = function(alunos){
    this.getTurma() > 0 ? this.alunos = alunos.split(",") : (function(){throw "you must set a 'turma' before inserting students on it"}());
};

然后它将正常工作。但是,仅仅因为您可以做某事并不意味着您应该做某事。我建议您保留以前的代码,因为它更具可读性。

于 2012-11-28T17:17:22.643 回答