javascript “ors” - can they be combined into an array?

wondering if I can make my javascript more efficient. I have a var JSP = "the jsp's name"

And I have statements in a javascript validation file:

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

Is there a more efficient way to do this?


If you know that JSP contains a string, it's slightly more efficient to use === rather than ==. Also note that you don't need all those parens:

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

You could also use a regular expression:

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

...but it depends what you mean by "efficient." The series of === will be very efficient at runtime.

Separately, you could use a switch:

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

...but I wouldn't call it more efficient.

I definitely would not put the options in an array, because searching through the array will not be efficient. But you can use a map:

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

...and then this test:

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

...which results in a fairly efficient property lookup. That's only reasonable if you create the object once and reuse it.

(You might have people say "Or just use if (pages[JSP]) { ... }. But that fails if JSP happens to contain "toString" or "valueOf" or any of several other inherited properties blank objects get from Object.prototype. It's fine if you're certain it won't have any of those values, though.)

Need Your Help

update model with ajax in razor

ajax jquery razor

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have picture u see what happen.

Number of unset bit left of most significant set bit?

c# c++ c 64bit bit-manipulation

Assuming the 64bit integer 0x000000000000FFFF which would be represented as