【问题标题】:Javascript syntax issue? [duplicate]Javascript语法问题? [复制]
【发布时间】:2013-09-10 22:25:53
【问题描述】:

IF 条件逻辑是否正确?它适用于 test1 但不适用于 test2 或 ""

      if($(this).attr("value") === ("test1" || "test2" || ""))
      {
          submitForm($(this).attr("value"));
      }

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您需要再次测试每个可能的值:

if($(this).attr("value") === "test1" || $(this).attr("value") === "test2" || $(this).attr("value") === ""))

用临时变量清理:

var attribute = $(this).attr("value");
if(attribute === "test1" || attribute === "test2" || attribute === ""))

或者,您可以使用indexOf() 作为简写:

if (["test1", "test2", ""].indexOf($(this).attr("value")) != -1)

【讨论】:

  • 这个没有捷径?
  • 看在上帝的份上,使用变量。
  • @user2736012,当然。我试图传达重复。
  • @YetimworkBeyene - 是的,有一个捷径:编写一个函数或使用 Bergi 评论中链接建议的 多个 替代方案之一。
  • 大家可以放松一下,问题已作为重复关闭。
【解决方案2】:
if($(this).attr("value") === ("test1" || "test2" || "")) {
    submitForm($(this).attr("value"));
}

这里发生了什么? OR || 操作符返回第一个 truthy 值,所以("test1" || "test2" || "") 的返回值是"test1"。在这种情况下,这个表达式是这样解释的:

(("test1" || "test2") || "")

评估的第一个表达式是"test1" || "test2",它返回"test1",因为它是一个真值。第二个表达式是"test1" || ""。它再次返回 "test1"(而且 ""falsy)。

写类似这样的东西的一种非常快速的方法是在数组中搜索:

var acceptedValues = ["test1", "test2", ""];
if(acceptedValues.indexOf(this.value) != -1) submitForm(this.value);

在这个简单的操作中不需要jQuery!

【讨论】:

  • 为了支持旧版浏览器,你应该使用 $.inArray()
【解决方案3】:
if($.inArray(this.value,['test1','test2','test3']) != -1){
    //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2013-08-29
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    相关资源
    最近更新 更多