===参数的多个实例中的效率



是否有一种更有效的显示方式:

$(this).text() === "something" || $(this).text() === "somethingelse"

这样的东西:

$(this).text() === ("something" || "something else")

Clarity的缘故:我并不是建议它应该像我所展示的那样。我想知道是否有一种更简单的方法可以做我的建议。因此,我不是重复同一命令。我只是想比较某些文本。

您可以创建选项数组,并检查您的值是否在该数组中。

["something", "something else"].indexOf($(this).text()) != -1

使用ES7,您可以使用includes()

["something", "something else"].includes($(this).text())

有几种可以实现欲望结果

的方法

方法1-使用indexof()

var myList = ["something", "somethingElse"];
if (myList.indexOf($(this).text()) !== -1) {
    //ok
} else {
    //nok
}

方法2-使用jquery.inarray

//This yields to false
$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );
//This yields to true
$.inArray( 5 + 5, [ "8", "9", "10", 10 ] );

发生这种情况的原因是因为JavaScript将0视为松散等于false

方法3-使用include()

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

方法4-开关

switch (expression) {
  case value1:
    //Statements executed when the result of expression matches value1
    [break;]
  case value2:
    //Statements executed when the result of expression matches value2
    [break;]
    default:
    //Statements executed when none of the values match the value of the expression
    [break;]
}

最新更新