0

I have a variable that is set dynamically on the page. I then have a list of colors in an array. I need to see if the color variable contains one of the items within the array.

Here's the code:

var colorlist = ['Silver', 'Gray', 'Black', 'Red', 'Purple', 'White'];
var col1 = "";
var color1 = 'Titanium Silver';
for (var c = 0; c < colorlist.length; c++) 
{
    if(color1.indexOf(colorlist[c]))
    {
        col1 = colorlist[c];
    }
    else
    {

    }
}

What I would expect this to return is "Silver", but it's consistently returning the last item in the array. What am I doing wrong?

4
  • If you are using a string, remember that IE<9 doesn't have indexOf you may want to use search Commented May 29, 2013 at 15:31
  • I tested in IE 7+ and it's all working just fine. Commented May 29, 2013 at 15:46
  • @NicoSantangelo: it doesn't have Array.indexOf, but String.indexOf is fine. Commented May 29, 2013 at 15:54
  • That's correct, I tried to say that you should be careful with arrays and wrote gibberish. My bad Commented May 29, 2013 at 16:59

1 Answer 1

3

Change your comparison to:

if(color1.indexOf(colorlist[c]) > -1)

-1 is returned when an item isn't found, yet -1 is truthy. The only falsey number is 0. So your comparison won't work as you expect.

Take a look at this fiddle, which prints the result of the indexOf and the truthyness of the value: http://jsfiddle.net/R3Xb3/

Notice how the first one returns true because "Silver" is found in the string (at a valid index). But then the rest aren't found, the index returned is -1, and the result is true.

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

3 Comments

So why would OP's loop return the last element?
@tymeJV Because the rest of the items in the array would return -1, which is truthy. And the OP doesn't break in the loop, so it continues
Stupid me! How did I miss that part! That's what happens when I stare at the same code for far too long. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.