I’m trying to search for a string in an array. If that string matches, I want to know which index number in that array has the matching string. I believe I should be using inArray(); but it’s always returning -1
var $eventwrap = $j('.tw-events'),
$daywrap = $j('.tw-day'),
$dayfilter = $j('#tw-filter-days li a');
$daywraphide = $j('tw-day.hide'),
$catwrap = $j('.tw-event-filter'),
$viewctrls = $j('.tw-view a'),
// RELEVANT CODE STARTS HERE
$clonedays = $j('.select-days').html(),
$clonebarrio = $j('.select-barrio').html(),
$clonecats = $j('.select-cats').html(),
$opday = $clonedays.split("</option>"),
$opbarrio = $clonebarrio.split("</option>"),
$opcategory = $clonecats.split("</option>");
// RELEVANT CODE ENDS HERE
filters = {};
// CHECK IF A GIVEN DAY HAS EVENTS
function filterToggle(element,x,y) {
$j(element).each(function(){
var $me = $j(this),
isli = $me.is('li');
if(isli) {
var myvalue = $me.find('a').attr('data-filter');
} else {
// RELEVANT CODE STARTS HERE
var myselect = $me.parent().attr('data-filter-group'),
myvalue = $me.attr('data-filter'),
myfilter = String(myvalue);
// RELEVANT CODE ENDS HERE
}
if(!x) {x = ''}
if(!y) {y = ''}
var eventcount = $j('.tw-event'+ myvalue + x + y).length;
if(eventcount == 0) {
if(isli) {
$me.addClass('empty tdn');
} else {
$me.remove();
}
} else {
if(isli) {
$me.removeClass('empty tdn');
} else {
// RELEVANT CODE STARTS HERE
var myarray = eval("(" + '$op' + myselect + ")");
alert($j.inArray(myfilter,myarray));
// RELEVANT CODE ENDS HERE
}
}
});
}
What am I doing wrong?
This may not help you solve your original question about inArray() returning -1, but I wanted to shed some light on the issues the other users had pointed out.
Alternatives to
eval()If your $op* variables exist in global scope you could use the window object and access them from there:
Better yet, you can remove your variables from global scope by placing them in a module. Maybe try something like this:
Variable Declarations
Javascript is function-level scoped; not blocked-level scoped. In block-level scoped languages variables declared inside a conditional block are local to that block. In JavaScript this is not the case, and you can run into some strange behavior, such as variable hoisting. I’m not going in to detail on JavaScript scoping, as this post is already getting too long, but this awesome article does a great job explaining it in detail.