javascript”;ors”-它们可以组合成一个数组吗

javascript "ors" - can they be combined into an array?

本文关键字:一个 数组 ors javascript 组合      更新时间:2023-09-26

想知道是否可以提高javascript的效率。我有一个var JSP="JSP的名称">

我在javascript验证文件中有语句:

if(( JSP == "test.html" ) || ( JSP == "test1.html") || ( JSP == "test2.html" )) then blah blah blah.

有没有更有效的方法可以做到这一点?

如果您知道JSP包含一个字符串,那么使用===而不是==会稍微高效一些。还要注意,您不需要所有这些parens:

if (JSP === "test.html" || JSP === "test1.html" || JSP === "test2.html") {
    // do something
}

您也可以使用正则表达式:

if (/^test[12]?'.html$/.test(JSP)) {
    // do something
}

但这取决于你所说的"高效"是什么意思。===系列在运行时会非常高效。

另外,可以使用switch:

switch (JSP) {
    case "test.html":
    case "test1.html":
    case "test2.html":
        // Do it
        break;
}

但我不会说它更有效率。

我肯定会而不是把选项放在数组中,因为在数组中搜索不会有效率。但你可以使用地图:

var pages = {
    "test.html":  true,
    "test1.html": true,
    "test2.html": true
};

然后这个测试:

if (pages[JSP] === true) {
    // do something
}

这导致相当有效的属性查找。只有当您创建对象一次并重用它时,这才是合理的。

(你可能会有人说"或者只使用if (pages[JSP]) { ... }。但如果JSP恰好包含"toString"或"valueOf",或者空白对象从Object.prototype获得的其他几个继承属性中的任何一个,那就失败了。不过,如果你确定它不会有任何这些值,那也没关系。(

您可以使用以下键创建对象:

var theThings = { "test.html": true, "test1.html": true, "test2.html": true };
if (theThings[JSP]) { /* whatever */ }

如果只有三到四个,那可能不值得,但如果有几十个,那肯定会更快,尤其是如果测试进行了几次。

编辑—哇,伙计们,我在里面哭了。属性名称查找将比数组中的线性搜索快。

var arr = ['test.html', 'test1.html', 'test2.html'];
if (arr.indexOf(JSP)) != -1) {
   alert("found it!");
}

此处的相关文档。

if( JSP in {"test.html":0, "test2.html":0, "test3.html":0} ) {
...
}

它与SQL的IN( 1, 2, 3)的关系并不比javascript:-(

中的更接近
if (["test.html", "test1.html", "test2.html"].indexOf(JSP) > -1)

对于在数组上不支持indexOf的浏览器,MDC建议使用添加缺失功能的短代码。

可能效率不高,但你有更干净的方法。例如,你可以使用这样的开关案例:

switch(JSP) {
    case 'test.html':
    case 'test1.html':
    case 'test2.html':
    blablabla; break;
}

或者你可以用url创建一个数组,看看你的字符串是否在数组中,就像这个一样

var arr = [
    'test.html', 'test1.html',
    'test2.html'
];
if(arr.indexOf(JSP) != -1) { blablabla; }

最后一个不会在所有浏览器中都起作用。

jQuery中的一种方法是使用inArray方法,例如:

if ($.inArray(JSP, ["test.html", "test1.html", "test2.html"]) > -1) {
    // your code
}

inArray方法的工作方式与String.indexOf类似,因此如果不匹配,则返回-1

使用正则表达式?

if (/^test'd?'.html$/.test(JSP)) { ... }

不过,我不能保证这会更高效,只是代码更整洁。

或者,如果您已经在使用jQuery,您可以使用jQuery.inArray((:

var names = ['test.html', 'test2.html', 'test3.html'];
if ($.inArray(JSP, names)) { ... }

或者使用undercore.js

var names = ['test.html', 'test2.html', 'test3.html'];
if (_.indexOf(names, JSP) !== -1) { ... }