2
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
  • 1
    For what it's worth, yes -1 means not found. Commented Jul 1, 2009 at 20:42

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

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?
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]; }
it also throws my program in an infinite loop! weird.
apparently arrays have .indexOf() in JavaScript 1.6 and later though: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…
@CoffeeAddict - It should have been "i < numberOfImagesToDisplay.length"
|
3
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);

1 Comment

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]; }
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.