开发者问题收集

Javascript 分割条件

2011-10-28
1021

现在,我有变量:

var possible_country = 'United States|Germany|Canada|United Kingdom';
var current_country = 'United States';

我想使用这样的条件作为函数

function dummy(c, p){
 var arr = p.split('|');

 /* Code I want */

 if(c === arr[0] || c === arr[1] || c === arr[2] || c === arr[3])
 {
  alert('Voila');
 }
}

所以我可以调用这样的虚拟函数

dummy(current_country, possible_country);
3个回答

我想您想要 indexof

122469740
pimvdb
2011-10-28

对数组使用 .indexOf 方法:

var possible_country = 'United States|Germany|Canada|United Kingdom';
var current_country = 'United States';

possible_country = possible_country.split('|'); //Split by |
alert(possible_country.indexOf(current_country)); //Search for the current_country inside fo possible_country.

作为函数:

function dummy(current, possible) {
    var arr = possible.split('|');
    if (arr.indexOf(current) != -1) {
        alert('voila');
    }
}
Madara's Ghost
2011-10-28

这个?

function dummy(c, p){
  var arr = p.split('|');
  for (var i in arr)
    if (arr[i]===c)
      alert("OK");
  alert("KO");
}
solendil
2011-10-28