您好,我正在尝试学习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();
发布于 2018-06-24 06:53:46
月份可以是负数,因此new Date(y-1, 11, 0)
与new Date(y, -1, 0)
相同:
var lastDay_of_LastMonth = new Date(y, m || -1, 0).getDate();
但是,要获得月份为1月(m == 0)时的12月天数,正确的版本是:
var lastDay_of_LastMonth = new Date(y, m, 0).getDate();
发布于 2018-06-24 06:29:34
为了避免重复,您只能通过在三元运算符本身中创建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();
不要害怕将长表达式分成多行
发布于 2018-06-24 06:38:04
当三元运算符(或压缩if)的组件包含许多部分时,它很快就会变得混乱。也许有些人不同意,但将三元运算符限制在更简单的情况下是很好的,比如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();
https://stackoverflow.com/questions/51005518
复制相似问题