簡體   English   中英

拋出錯誤消息無法在OOP Javascript三元運算符上編譯

[英]Throw error message doesn't compile on OOP Javascript ternary operators

為什么這樣編譯:

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";
};

你實際上不能直接在三元運算符中拋出錯誤,就像你試圖在那里做的那樣。 但是,你可以在一個匿名函數中包裝throw ,如下所示:

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

然后它會正常工作。 但是,僅僅因為你可以做某事並不意味着你應該做 我建議保留以前的代碼,因為它更具可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM