If statement variables and array

时间:2019-01-18 19:14:13

标签: javascript arrays

I'm trying to dynamically show or hide an element based on the current site title. There are more than 4 pages but only using 4 as an example:

var stringTitle = window.location.pathname; 
var home1 = "/sites/xxx/pages/home.aspx";
var home2 = "/sites/xxx/employees/pages/home.aspx";
var home3 = "/sites/xxx/directory/pages/home.aspx";
var home4 = "/sites/xxx/forms/pages/home.aspx";

if (stringTitle == home1 || stringTitle == home2 || stringTitle == home3) {
    //Display Something
}

Since this could potentially be really long, is there a way I can use variables in array then use it in If statement? I tried the following but didn't work and also found out includes() doesn't work in IE:

var hmArray = [home1, home2, home3, ...];
var n = hmArray.includes(stringTitle); //true or false
if (n == 1) {
  //display stuff
}

2 个答案:

答案 0 :(得分:1)

您可以使用indexOf();

if (hmArray.indexOf(stringTitle) !== -1) {
  // display stuff
}

答案 1 :(得分:0)

如果需要,您可以为include制作一个polyfill。

Array.prototype.includes = Array.prototype.includes || function(value){
    return this.indexOf(value) > -1;
};

然后包含浏览器的浏览器将使用本机浏览器,而不包含浏览器的浏览器。