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 } 
      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
      • This won't work. You've got an error in your indexOf check and your missing closing parenthesisCommentedJan 15, 2014 at 9:44
      0
       for(var i=0;i<colors.length;i++) { if(localStorage.themeColor==colors[i]) { alert(colors[i]); } else{ alert("colors not set"); } 
        0

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

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

          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

            -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
            • Sorry, I had to downvote this because you're basically rewriting an existing function.CommentedJan 15, 2014 at 9:47
            • existing function you mean contains() ?
              – Ajey
              CommentedJan 15, 2014 at 9:50
            • No, indexOf (as linked to in multiple answers here) does exactly thisCommentedJan 15, 2014 at 9:51