如何重构我的条件声明?

时间:2013-09-17 16:59:28

标签: javascript

我试图用这个条件语句缩短我的代码

我有

  if(title =='project'){
      title = text + ': ' + this.projectTitle;
  }else{
      title = this.projectTitle;
  }

我觉得有更好的方法可以重写这个。有谁知道怎么做?

谢谢!

5 个答案:

答案 0 :(得分:1)

尝试ternary

title = (title =='project') ? text + ': ' + this.projectTitle: this.projectTitle;

答案 1 :(得分:1)

复制if / else

的三元组
title = title == 'project' ? text + ': ' + this.projectTitle : this.projectTitle;

虽然你真的想缩短它:

title = (title == 'project' ? text + ': ' : '') + this.projectTitle;

参考文献:

答案 2 :(得分:1)

简单的内联条件;

   title =  ((title =='project') ? text + ': ' + this.projectTitle : this.projectTitle);

查看link了解详情

答案 3 :(得分:1)

title = (title == 'project' ? text + ': ' : '') + this.projectTitle;

答案 4 :(得分:1)

var title = (title =='project' ? text + ': ' + this.projectTitle : this.projectTitle);