tags:

views:

205

answers:

3
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.

+1  A: 

.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()

Mike Robinson
nice. Was not aware of that. Is there a shortuct to having to use jQuery. such as can you use $.inArray() or something like that?
CoffeeAddict
tried this but it loops infinitely and gives me a -1 every damn time: for(i = 0; i < numberOfImagesToDisplay; i++) { if (i > 0) { addIndex = productIDs.length + 1; } alert(allProductIDs[jQuery.inArray(lastProductID) + i]); productIDs[addIndex] = allProductIDs[jQuery.inArray(lastProductID) + i]; }
CoffeeAddict
it also throws my program in an infinite loop! weird.
CoffeeAddict
apparently arrays have .indexOf() in JavaScript 1.6 and later though:https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf
newacct
@CoffeeAddict - It should have been "i < numberOfImagesToDisplay.length"
Mike Robinson
@newacct: Not in IE6 though <shakes fist at Bill Gates>
Mike Robinson
A: 

Check your syntax too. You are missing an end bracket ..']'

timbo
that was a post error.
CoffeeAddict
+1  A: 
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);
Scott Evernden
any idea why my program would be thrown into an infinite loop with the following : for(i = 0; i < numberOfImagesToDisplay; i++) { if (i > 0) { addIndex = productIDs.length + 1; } //alert(allProductIDs[jQuery.inArray(lastProductID) + i]); productIDs[addIndex] = allProductIDs[jQuery.inArray(lastProductID) + i]; }
CoffeeAddict