![](/img/trans.png)
[英]How can I change the if else statement in the function with Ternary operator in JavaScript?
[英]How can I rewrite this JavaScript line for simpler reading? ( Ternary Operator )
嗨,我正在尝试使用此Calendar代码作为研究/项目材料来学习JavaScript。 这个变量中发生了很多事情,就像看着某种外语一样。 如何改写此行以便于阅读?
https://codepen.io/xmark/pen/WQaXdv
// Last day of the Previous Month.
// , lastDayOfLastMonth = ...
var lastDay_of_LastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
为了避免重复自己,您只能通过在三元运算符本身中创建new Date
来编写getDate
一次,然后在整个表达式上调用getDate
:
var lastDay_of_LastMonth =
(m === 0 ? new Date(y-1, 11, 0) : new Date(y, m, 0))
.getDate();
但是,您也可以为有问题的date
对象定义一个独立变量,以明确表示它的含义:
var lastMonthDate = m === 0
? new Date(y - 1, 11, 0)
: new Date(y, m, 0)
var lastDay_of_LastMonth = lastMonthDate.getDate();
不要害怕将长表达式分成多行
月可以是负数,因此new Date(y-1, 11, 0)
与new Date(y, -1, 0)
:
var lastDay_of_LastMonth = new Date(y, m || -1, 0).getDate();
但是要获得当月份为一月(m == 0)的12月的天数,则正确的版本为:
var lastDay_of_LastMonth = new Date(y, m, 0).getDate();
当三元运算符的组成部分很多时,它们很快就会变得混乱。 也许有些人会不同意,但是最好将三元运算符限制在更简单的情况下,例如var parity = x % 2 === 0 ? "even" : "odd"
var parity = x % 2 === 0 ? "even" : "odd"
在您的情况下,我认为将整个if语句写出来最容易理解:
var lastDay_of_LastMonth
if (m == 0)
lastDay_of_LastMonth = new Date(y-1, 11, 0).getDate();
else
lastDay_of_LastMonth = new Date(y, m, 0).getDate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.