遍历数组并将变量与数组进行比较

时间:2018-09-04 10:01:51

标签: javascript

正如主题所暗示的,我有一个数组,我想将包含字符串的变量与之进行比较。我似乎无法触发警报,所以我假设在if语句中进行的比较是错误的。

如果有人可以纠正我,将不胜感激。

这里的前4个变量是向您显示字符串的来源。

var urlStr = window.location.href; ///index.html?_Spain_Germany_Russia
var urlStrDecode = decodeURI(urlStr);
var urlStrSplit = urlStrDecode.split('_');
var country = urlStrSplit[1];
function runFunction(){
    var countryList = ["Spain", "the United States", "France"];
    var countryListLength = countryList.length;
    for (var i = 0; i < countryListLength; i++) {
        if (country === countryList) {
            console.log('The country was matched');
        }
    }
}
runFunction();

谢谢。

尼尔。

3 个答案:

答案 0 :(得分:0)

您应指定索引以从数组中检索值。 countryList[i]将为您提供国家/地区

if (country === countryList[i]) {
            console.log('The country was matched');
  }

答案 1 :(得分:0)

如注释所示-您需要对照数组的每个项目检查国家/地区,但这是一个略微不同且更现代的循环,不需要数组或索引数组的长度。 / p>

var urlStr = window.location.href; ///index.html?_Spain_Germany_Russia
var urlStrDecode = decodeURI(urlStr);
var urlStrSplit = urlStrDecode.split('_');
var countryName = urlStrSplit[1];
function runFunction(){
    var countryList = ["Spain", "the United States", "France"];

    countryList.forEach(function(country){
       if(country === countryName) {
          console.log('The country was matched');
        }
    }}
}
runFunction();

或良好的旧indexOf ...

var urlStr = window.location.href; ///index.html?_Spain_Germany_Russia
var urlStrDecode = decodeURI(urlStr);
var urlStrSplit = urlStrDecode.split('_');
var countryName = urlStrSplit[1];
function runFunction(){
    var countryList = ["Spain", "the United States", "France"];

    if(countryList.indexOf(countryName) !== -1) {
        console.log('The country was matched');
     }
    }
    runFunction();

答案 2 :(得分:0)

将国家/地区与for循环中的当前元素进行比较。

var urlStr = 'index.html?_Spain_Germany_Russia'
var urlStrDecode = decodeURI(urlStr);
var urlStrSplit = urlStrDecode.split('_');
var country = urlStrSplit[1];
function runFunction(){
    var countryList = ["Spain", "the United States", "France"];
    var countryListLength = countryList.length;
    for (var i = 0; i < countryListLength; i++) {
        if (country === countryList[i]) {
            console.log('The country was matched');
        }
    }
}
runFunction();

您可以使用内置的数组方法Array.includes()。 includes() 方法确定数组是否包含某个元素,然后返回 正确或错误

countryList.includes(country) // true