I have a large array called “data”.
At the 10th array position i have this at its data value:
[10] => 1,2
Now what im trying to do in JS is something like this:
i = 1;
if(i in data[10]){
//great success, very nice!
}
I thought comma separated data might act like an array with the “IN” method, but its not working. I get this error:
Uncaught TypeError: Cannot use 'in' operator to search for '1' in 1,2
What would be the correct solution for my problem ?
You don’t show the code for how you assign
1,2todata[10]. The value of1,2is simply2as you can see from executing the following in a JavaScript shell/console. See the reference for how the comma operator works.However, the error message you are getting suggests that you have the string
"1,2". To turn it into an array, you should usesplit()as in:To iterate over the values you can use the
inoperator on the resulting Array as in:You can run this in a browser console and the
alertwill show you two messages:Note that you don’t need to initialize
ibefore the loop begins. Theinoperator will do this automatically. Also, it’s good practice to use local variables hence thevar iin the code above.On a side note, if you are new to JS but you need to deal with a lot of data structure manipulation, it’s worth learning about underscore.js. Take a look at
_.each()in particular. Underscore can save you from writing a lot of looping logic.If, however, you want to do a membership check then you need to use not
inbutArray.indexOf(). See http://jsfiddle.net/nRS9m for an example forked from your jsfiddle in the comments. More examples: