简体   繁体   中英

javascript validate value against array

I'm looking for a way to verify against an array. I'm lost in the array searching part.

I may get an array like this:

stream = ["apple","orange", "grape", "peach","strawberry","watermelon", "kiwi", "raspberry"];

But I only want :

selection = ["apple", "peach","strawberry","kiwi", "raspberry"];

How would I write a statement that would say: If something in this stream matches my selection, do something.

You must use the inArray command like this:

if($.inArray(ValueToCheck, YourArray) > -1) { alert("Value exists"); }

InArray will search your array for the value you asked for and return its index. If the value isn't present, it returns -1.

var stream    = ["apple","orange", "grape", "peach","strawberry","watermelon", "kiwi", "raspberry"],
    selection = ["apple", "peach","strawberry","kiwi", "raspberry"];

stream.forEach(function(elem) {
    if( selection.indexOf(elem) > -1 ) {
        // we have a match, do something.
    }
});

Note that Array.prototype.forEach help and .indexOf() help are part of Javascript 1.6 and may not be supported by any InternetExplorer < version 9. See MDC 's documentation on alternative versions.

There are lots of other ways to accomplish the same thing (using a "normal" for-loop for instance) but I figured this is probably the best trade-of in performans vs. readability.

Anyway, all the used Javascript 1.6 functions are actually very trivial to write on your own.

jQuerys $.inArray() help will also use Array.prototype.indexOf() if it's supported by the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM