首页 > 解决方案 > 是否可以缩短 javascript 以避免 if 和 else?

问题描述

我正在尝试在 javascript 中转换 PHP 片段:

function year_shortcode() {
    $fromYear = 2010;
    $thisYear = (int)date('Y');
    return $fromYear . (($fromYear != $thisYear) ? '-' . $thisYear : '');
} add_shortcode('year', 'year_shortcode');

到目前为止我所做的是:

var fromYear='2010';
var thisYear= new Date().getFullYear();

if (fromYear=thisYear) {
    document.write(fromYear);
}
else {
    document.write(fromYear + '-' + thisYear);
}

我想避免 if 和 else 语句,并像在 PHP 中那样缩短它。

标签: javascript

解决方案


你可以这样做

需要注意的一件事=是赋值运算符,如果要检查两个值之间的相等性,请===改用

document.write(fromYear === thisYear ? fromYear : fromYear + '-' + thisYear)

推荐阅读