user4759415
user4759415

Reputation:

Using jQuery $.inArray

I need to compare a dynamically created variable against an array of static values. As the variable is dynamically generated I can't do something like

if ($.inArray('example', myArray) != -1)
{
  // found it
}

What I have so far is this

 //This runs for each link in the .lc_Cell element
  $('.lc_Cell > p > a').attr('href', function(i, href) {

        //Grab the link and split it into chunks at each occurence of '&'
        var arr = href.split('&');
        console.log(arr);

        //Keep a portion of the link as a var, this is always a 4 digit number
        //For the purposes of this question lets say this value is going to be 7473 
        var trId = arr[1].slice(-4); 
        console.log(trId);

        //Populating my array of desired numbers to search against
        var validTR = [7473, 7474, 7475, 7476, 7477, 7478, 7479, 7480, 7481, 7482, 7483, 7484, 7485, 7486, 7487, 7488, 7489, 7490, 7491, 7492, 7493, 7494, 7495, 7351]; 
        console.log(validTR);       


        //Compare the sliced value from the link against the array
        var testingID = $.inArray(trId, validTR)
        console.log(testingID);
}

My testingID in the console consistently keeps returning -1, even if the the value in trId is one contained within the array.

Ultimately, I need to be able to get a positive value for testingID so I can write an if statement to do something afterwards.

Upvotes: 2

Views: 188

Answers (2)

Brett Gregson
Brett Gregson

Reputation: 5913

As per the docs:

The comparison between values is strict.

Your trId value is a string, the array values are numbers. This is because jQuery.attr() returns a string (except in special cases).

Try wrapping your array values in quotes to make them strings or cast all to strings or numbers:

trId = parseInt(trId, 10);

or

var validTR = ["7473", "7474", ...

A fiddle demonstrating the problem can be found here

Upvotes: 1

Quentin
Quentin

Reputation: 943143

  • The validTR array contains only numbers.
  • The return value of slice() will be a string.

A string representation of a number is not the same as a number, so it won't be found when you search the array.

const array = [1,2,3];
const number = 2;
const string = "2";

console.log("A", $.inArray(string, array));
console.log("B", $.inArray(number, array));
console.log("C", $.inArray(+string, array));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Either populate the array with strings, or convert the string to a number.

Upvotes: 0

Related Questions