2011-10-28 43 views
0

在這裏,我們走了,我有變數:的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); 
+0

你不能只通過所有的國家循環? (我的意思是在* arr *)並且使用這個條件,但是像* if(c == arr [i])* –

+0

我可能更喜歡'var isValidCountry =/^(美國|德國|加拿大| United Kingdom)$ /'with'if(isValidCountry.test(country))'。 –

回答

1

我想你想indexOf

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

if(~arr.indexOf(p)) { // arr contains p as one of its elements 
    alert('Voila'); 
} 
} 
用於陣列
+0

+1,使用'〜'有趣。 –

+0

我錯過了什麼? '〜'是按位不是嗎?這是如何運作的?在JS 1.6之前,indexOf甚至不可用於數組。 –

+0

'〜-1'將始終爲假(因爲-1是真實的 - 在*所有位都被設置爲有意義的情況下)其他所有(非-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'); 
    } 
} 
0

這?

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

如果保持管杆末

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

你只需要一條線檢查:

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