1

I have the following in javascript:

 var colors = ["dark", "light"];

 if (localStorage.themeColor) {

How can I modify this to not only check that localStorage.themeColor is set but also to check that it is one of the two values in the array?

6 Answers 6

1

You can use indexOf in conjunction with your existing check for themeColor:

if(localStorage.themeColor && colors.indexOf(localStorage.themeColor) > -1) {
    // Do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can say something like:

var colors = ["dark", "light"];

if (localStorage.themeColor && colors.indexOf(localStorage.themeColor) != -1) {

For indexOf see:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf

1 Comment

This won't work. You've got an error in your indexOf check and your missing closing parenthesis
0
    for(var i=0;i<colors.length;i++)
{
if(localStorage.themeColor==colors[i])
{
alert(colors[i]);
}
else{
alert("colors not set");
}

Comments

0

colors.indexOf("dark") !== -1

indexOf returns -1 if the argument passed does not exist in colors

Comments

0

You can solve it like this

var colors = ["dark", "light"];

if (localStorage.themeColor && colors.indexOf(localStorage.themeColor) > -1) {
    // Your Code...
}

I tested it in the case of localStorage.themeColor == light and localStorage.themeColor is undefined

Comments

-1

you should create a prototype like this

Array.prototype.contains = function(elem)
    {
       for (var i in this)
       {
          if (this[i] == elem) return true;
       }
       return false;
    }

And your array here

var colors = ["dark", "light"];

Finally call the function using colors.contains("dark") // this will return true

3 Comments

Sorry, I had to downvote this because you're basically rewriting an existing function.
existing function you mean contains() ?
No, indexOf (as linked to in multiple answers here) does exactly this

Your Answer

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