javascript - 是否可以缩短 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 中那样缩短它。
解决方案
你可以这样做
需要注意的一件事=
是赋值运算符,如果要检查两个值之间的相等性,请===
改用
document.write(fromYear === thisYear ? fromYear : fromYear + '-' + thisYear)
推荐阅读
- javascript - 解决承诺 React Native
- java - 无法从我的 Java 类访问 org.springframework.data
- java - 在 Java 中使用并行流但未获得预期值
- javascript - 在条件下显示数据表中的特定子行
- html - 响应式顶栏
- sas - Proc Report 如何隐藏行?
- latex - 如何在循环中用 LaTeX 编写一系列符号
- oracle - oracle 11g中格式“YYYY-MM-DD”的字段的最佳数据类型是什么?
- node.js - nodejs/express mongoose .populate() 在带有自身引用的架构上
- javascript - ReactJS:使用枚举的条件渲染