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?
You can use indexOf in conjunction with your existing check for themeColor:
if(localStorage.themeColor && colors.indexOf(localStorage.themeColor) > -1) { // Do stuff }
You can say something like:
var colors = ["dark", "light"]; if (localStorage.themeColor && colors.indexOf(localStorage.themeColor) != -1) {
For indexOf see:
for(var i=0;i<colors.length;i++) { if(localStorage.themeColor==colors[i]) { alert(colors[i]); } else{ alert("colors not set"); }
colors.indexOf("dark") !== -1
indexOf returns -1 if the argument passed does not exist in colors
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
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