var truth = true;
(truth) ? console.log('It is true') : throw new Error('It is not true');
三元運算符只接受特定類型的對象嗎?爲什麼這個三元運算符在JS中無效
var truth = true;
(truth) ? console.log('It is true') : throw new Error('It is not true');
三元運算符只接受特定類型的對象嗎?爲什麼這個三元運算符在JS中無效
javascript區分語句和表達式。三元運算符只處理表達式;扔是一個聲明。
與所有其他運算符一樣,條件運算符只能與表達式一起使用。
throw x;
是聲明,不是表達式。
它確實有效,但問題在於「else」分支中的throw語句。
使用
(truth) ? console.log('It is true') : (function(){throw 'It is not true'}());
這使得@Freddie代碼有效,但並不能解釋三元需要是表達式而不是語句。 – OnaBai
你可以做一個函數:'功能_throw(MSG){拋出新的錯誤(MSG); }'然後在條件運算符中使用它:'真相? console.log(「true」):_throw(「It is not true」);' –