如果在if语句

时间:2017-08-01 05:02:09

标签: javascript ecmascript-6 es5-shim

我想知道是否有更简洁的方法来编写这个javascript代码。 if内的if似乎相当平均。如果可能的话,很高兴使用es5/es6。基本上,我检查变量是否存在,如果确实存在,我想确保网址包含https,如果不存在则更新它。

if (blogURL) {
  if (!/^https?:\/\//i.test(blogURL)) {
      var blogURL = 'http://' + blogURL;
  }
}

4 个答案:

答案 0 :(得分:3)

使用fine_id在单个&&语句中测试这两个条件并删除var,因为您可能只想更新现有变量,而不是看起来您正在尝试定义新变量。

if

这是有效的,因为如果第一个条件测试失败,则不执行第二个条件测试。这是在Javascript中执行此类操作的常用方法。

答案 1 :(得分:0)

if (blogURL && !/^https?:\/\//i.test(blogURL)) {
     blogURL = 'http://' + blogURL;
}

将您的条件与&&和运营商。因为&&从左到右进行评估,只有在前一个为真时才会测试下一个条件。

答案 2 :(得分:0)

始终可以执行内联"ajax":{ url :_ajaxURL, // json datasource type: "post", // type of method , by default would be get error: function(){ // error handling code $("#astab_processing").css("display","none"); } } 声明:

if

或其他人推荐的var exist = blogURL != null ? !/^https?:\/\//i.test(blogURL) : false; if(exist){ }

答案 3 :(得分:0)

这是最优化整洁的解决方案之一:

blogURL = (blogURL && !blogURL.startsWith("https://")) ? ('http://' + blogURL) : blogURL;
相关问题