0

Possible Duplicate:
array.contains(obj) in JavaScript
Finding an item of an array of numbers without using a loop

i'm wondering if its possible to check if xy[i] matchs any element of an array without using for loop in JavaScript? . with example, please?

thanks

Community
  • 1
  • 1
shamsi
  • 1
  • 1
  • What's wrong with using a loop? – Raymond Chen Nov 13 '12 at 22:20
  • 2
    This question amazes me every time... Why is it such a bad thing to use a loop? Put the loop in a function if you're fretting over the beauty of your code! – jahroy Nov 13 '12 at 22:23
  • No. Edit: let me clarify, although you can use wrapper function as mentioned by previous users, the internal implementation will have to use some sort of loops for a dynamic array. – dchhetri Nov 13 '12 at 22:19
  • edit: in any situation, the code has to loop. My original answer was No, but that wouldn't be accepted. – dchhetri Nov 13 '12 at 22:20

1 Answers1

1

You can either use a loop or use a function that uses a loop.

Some libraries, like jQuery, offer their own functions (that use loops).

Using a loop is not a bad thing.

You can keep your code pretty (and organized) by putting the loop in a function.

var stringArray = [ "one", "two", "three" ];
var searchTerm = "two";

if (contains(stringArray, searchTerm)) {
    alert("found it");
}

function contains(someArray, someTerm) {
    for (var i = 0; i < someArray.length; i++) {
        if (someArray[i] === someTerm) {
            return true;
        }
    return false;
}
jahroy
  • 22,322
  • 9
  • 59
  • 108