如何重写此JavaScript行以简化阅读? (三元运算符)

时间:2018-06-23 22:23:15

标签: javascript

您好,我正在尝试使用此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();

3 个答案:

答案 0 :(得分:2)

要避免重复自己,您只能通过在三元运算符本身中创建getDate来编写new Date一次,然后在整个表达式上调用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();

不要害怕将长表达式分成多行

答案 1 :(得分:2)

月份可以为负数,因此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();

答案 2 :(得分:1)

当三元运算符的组成部分很多时,它们很快就会变得混乱。也许有些人会不同意,但最好将三元运算符限制在简单的情况下,例如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();