2015-09-08 78 views
0

我有一個字符串數組這樣檢查是否與JavaScript變量條件

function checkAlreadyShortlisted() 
{ 
    var shortListed = new Array();      
    shortListed = '["Mr. Andrew Severinsen", "Mr. Tom Herron", "Ms. Samantha Smithson-Biggs", "Mr. Efrem Bonfiglioli", "Mr. Giles Forster"]'; 
    var candidateName = ''; 

    $('.searchResultCandidateDiv').each(function(i, obj) { 

     candidateName = $(this).find('.viewResumeAnchor').text(); // Get the text from the particular div 
     console.log(candidateName); 

     if(candidateName == shortListed[4]) // Copied the value from Set 
      { 
      console.log('Got from Set'); 
     }    
     else if(shortListed[4] == "Mr. Giles Forster") // Copied the value from anchor 
     { 
      console.log('Got from Anchron text'); 
     } 
    }); 
} 

在div環狀我不得不檢查是否入圍陣列中的名稱是存在或不存在。

這些都是我從瀏覽器控制檯日誌複製

埃弗雷姆先生邦飛利

賈爾斯先生福斯特

與上面的文字檢查條件工作正常價值,但如果我嘗試用數組字符串檢查值是不能正常工作的。但文字是否有類似的想法?

回答

1

變量shortListed不是持有數組值,而是持有字符串。刪除報價'周圍:

shortListed = ["Mr. Andrew Severinsen", "Mr. Tom Herron", "Ms. Samantha Smithson-Biggs", "Mr. Efrem Bonfiglioli", "Mr. Giles Forster"]; 

然後你能夠通過shortListed[0], shortListed[1], shortListed[n],..

更簡單的方式訪問它來檢查數組值包含的東西,我想用$.inArray()內置函數jQuery中。 如果該值不存在,該函數將返回-1,否則返回索引如果發現該值。見下面的例子如何使用:

if ($.inArray('Mr. Tom Herron',shortListed) !== -1) {  
    alert('Found it'); 
} 

DEMO

相關問題