var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140];
lastProductID = 6758;
for some reason I get a -1 or I guess which is equivalent to not found for this:
alert(allProductIDs[allProductIDs.indexOf(lastProductID));
I can't figure out for the life of my why because it should find 6758 and that would be index 3. If it's index 3 then I should get back 6758 I would think.
var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140];
lastProductID = 6758;
for some reason I get a -1 or I guess which is equivalent to not found for this:
alert(allProductIDs[allProductIDs.indexOf(lastProductID));
I can't figure out for the life of my why because it should find 6758 and that would be index 3. If it's index 3 then I should get back 6758 I would think.
Share Improve this question asked Jul 1, 2009 at 20:35 PositiveGuyPositiveGuy 47.8k112 gold badges314 silver badges479 bronze badges 1- 1 For what it's worth, yes -1 means not found. – Nosredna Commented Jul 1, 2009 at 20:42
3 Answers
Reset to default 5.indexOf()
is used for strings, not arrays.
Using regular Javascript you'll have to loop through the array until you find a match, or use the inArray()
function of jQuery.
jQuery inArray()
var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140];
lastProductID = 6758;
for (i in allProductIDs)
{
if (allProductIDs[i] == lastProductID) {
alert(allProductIDs[i] + " is at index " + i);
break;
}
}
or
i = $.inArray(lastProductID, allProductIDs)
alert(allProductIDs[i] + " is at index " + i);
Check your syntax too. You are missing an end bracket ..']'