1

So I have the following array defined as follows:

        var a = new Array();
            a[1] = new Array();

            a[1][0] = "Computer Science";
            a[1][1] = "Computer Engineering";
            a[1][2] = "Aerospace Engineering";
            a[1][3] = "Engineering (Other)";
            a[1][4] = "Web Development";
            a[1][5] = "Computer Programming";
            a[1][6] = "Android Development";
                    //a[2] through a[n] defined similarly

and at one point, I'm trying to test if a string is contained anywhere in a[i], say "Computer Science", so I do the following:

                 for(j=1; j<n; j++)
                    if("Computer Science" in a[j])
                    {
                              //DO SOMETHING
                    }

However, this ALWAYS returns false, and yet I've verified that a[j] DOES in fact contain the string (in a[j][0]). Any idea why this is happening?

2
  • Take it back to the basics. Try this: alert('Computer Science' in ['Computer Science']);. Nope! Also, new Array() should probably just be [] as in var a = [];. Commented Jul 13, 2012 at 8:44
  • 1
    Why [1]? Anyway it is more elegant to do var a=[["computer...","computer...",...["android...]] like ErikE mentioned in the meantime Commented Jul 13, 2012 at 8:51

2 Answers 2

8

The in operator is used for testing whether a property (name) exists on an object. For example, "5" in a[j] were true - the array has an index 5.

You want to use the indexOf method to check whether an element exists in an array:

if (a[j].indexOf("Computer Science") > -1)
    //DO SOMETHING
3
  • Array.indexOf is not available in all browsers, notably not in IE<9. See developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… Commented Jul 13, 2012 at 8:45
  • So shame on IE, I can only say :-) Does my answer need to include the shim to be complete? Commented Jul 13, 2012 at 9:15
  • 1
    the shim is in the link of my comment, so I'd say no. You could've made the point in your answer. IE unfortunately is still an unavoidable nuissance for web developers Commented Jul 13, 2012 at 9:20
0

this works:

var a = [];
a[0] = [];
a[1] = [];

a[1][0] = "Computer Science";
a[1][1] = "Computer Engineering";
a[1][2] = "Aerospace Engineering";
a[1][3] = "Engineering (Other)";
a[1][4] = "Web Development";
a[1][5] = "Computer Programming";
a[1][6] = "Android Development";

for(j=0; j<a.length; j++) {
    if("Computer Science" in oc(a[j])) {
       alert("test");               
    }
}

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

http://jsfiddle.net/SRPEU/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.