Javascript:内部的三元运算符" if"条件

时间:2015-12-23 16:57:57

标签: javascript if-statement ternary-operator

我发现了这个Javacript代码,我无法理解在if条件下有三元运算符意味着什么。

var s = 10, r = 0, c = 1, h = 1, o = 1;

if (s > r ? (c = 5, h = 2) : h = 1, o >= h)
{
  alert(1);
}

返回o >= h结果是否在&#34中评估;如果"条件? 那么在#34;中使用逗号怎么样?条件?

2 个答案:

答案 0 :(得分:2)

这真的只是一种语法上的捷径。可以将其扩展为两个% table 3 begins \begin{table}[h] \centering \caption{} \label{my-label} \begin{tabular}{cccc} \hline \textbf{Properties} & \textbf{Model 1} & \textbf{Model 2} & \textbf{Model 3} \\ \hline \begin{tabular}[c]{@{}c@{}}Training\\ Window width\end{tabular} & 2 & 2 & 1 \\ \begin{tabular}[c]{@{}c@{}}Training\\ window step\end{tabular} & 1 & 1 & 1 \\ \begin{tabular}[c]{@{}c@{}}Test\\ window width\end{tabular} & 2 & 2 & 1 \\ Horizon & 5 & 10 & 15 \\ \begin{tabular}[c]{@{}c@{}}Cumulative\\ training\end{tabular} & No & No & No \\ \hline \end{tabular} \end{table} \\ % table 4 begins \begin{table}[!t] \centering \caption{} \label{my-label} \begin{tabular}{ccccc} \hline \textbf{Date} & \textbf{\begin{tabular}[c]{@{}c@{}}Actual Price\\ (USD)\end{tabular}} & \multicolumn{3}{c}{\textbf{Predicted Price}} \\ \hline \textbf{} & \textbf{} & \textbf{Model 1} & \textbf{Model 1} & \textbf{Model 1} \\ 13-01-15 & 89.30 & 89.44 & 87.90 & 91.71 \\ 07-11-14 & 78.76 & 77.63 & 77.72 & 78.08 \\ 29-07-14 & 75.44 & 75.00 & 76.43 & 77.59 \\ 04-06-14 & 77.12 & 76.26 & 76.96 & 77.53 \\ \hline \end{tabular} \end{table} 语句:

if

使用var condition; if (s > r) { c = 5; condition = (h = 2); // another short-cut; it's essentially (h = 2, condition = true) } else { h = 1; condition = (o >= h); } if (condition) { alert(1); } 允许将两个语句转换为单个语句(因为comma总是评估为a, b,但ba子表达式都是b在过程中评估。)

答案 1 :(得分:-1)

当你运行时,这段代码不会出错...基本上...做的是运行它找到的三元运算(c = 5,h = 2),这不是写入if语句的条件。 。
因此条件不会满足,它不会警觉(1);

相关问题