Javascript拆分条件

时间:2011-10-28 10:14:21

标签: javascript

我们走了,我有变量:

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);

4 个答案:

答案 0 :(得分:1)

我想你想要indexOf

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

 if(~arr.indexOf(p)) { // arr contains p as one of its elements
  alert('Voila');
 }
}

答案 1 :(得分:1)

对数组使用.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');
    }
}

答案 2 :(得分:0)

这个?

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

答案 3 :(得分:0)

如果你把管杆放在最后

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

你只需要一行检查:

if (possible_country.indexOf(current_country + '|') > -1)
{
    alert('Voila');
}