views:

92

answers:

4

In JavaScript let's say we have the following code

var test = 'd';
if (test != 'a' && test != 'b' && test != 'c')
  alert('were good to go');

This if seems rather lengthy to me. I would love to write something like

if (test != ('a' && 'b' && 'c')
  alert('were good to go');

Sadly this doesn't work. What is a more elegant way to write this?

+2  A: 

You can't get do that, but you can get fairly close like this:

Array.prototype.contains = function(v) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == v) return true;
    }
    return false;
}

if (!['a', 'b', 'c'].contains('d')) {
    alert('good to go');
}

Most decent JS libs should contains lots of variations on list prototypes like this.

Svend
...with the standard caveat that messing with the prototypes of builtins is a good way to confuse yourself horribly later.
DDaviesBrackett
Usually a matter of just understanding the language. If you've come fresh over from a statically typed language, with class based OO inheritance, then sure, this can be strange. But it's easy to change to a function approach instead. I think this is much cleaner however. It's how Javascript works.
Svend
There is no reason to fear modifying prototypes of built in objects. The only exception is the Object prototype which causes issues for iterators.
Prestaul
+2  A: 
var test = 'd';
if (!/[abc]/.test(test))
  alert('were good to go');
Fabien Ménager
Why not if(!/[abc]/.test(test))? "test" should be more efficient here than "match".
Prestaul
Yep, test() works too ! Thank you
Fabien Ménager
A: 

One little helper function will take you far...

// If you write this...
function set(){
    obj={}
    for (var i=0; i<arguments.length; i++)
        obj[arguments[i]]=1;  
    return obj
}

// Then you can do this!
if (! test in set('a','b','c')){
    //Do stuff.
}
Triptych
I have some kind of irrational fear of the in operator, for some reason.
Jimmy
As Prestaul mentions above, anything attached to the Object prototype will show up in a for/in of anything else, so for/in, has a bit of a bad rep, and I usually only use it for debugging.
Svend
+1  A: 

I concur with Matthew Crumley that this is a logically invalid question, as-is. For fun I'm going to assume you meant to use && in your question...

var test = 'd';
({a: 1, b: 1, c: 1}[ test ]) || alert("we're good to go");

or..

var test = 'd';
!(test in {a: 0, b: 0, c: 0}) && alert("we're good to go");
ken
I vote for your solution. Mostly because you finally fixed the typo in the alert string.
Nosredna