简体   繁体   中英

Checking if condition with javascript variables

I have a string array like this

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

In the div looped I have to check if the name in the shortlisted array is present or not.

These are values I copied from browser console log

Mr. Efrem Bonfiglioli

Mr. Giles Forster

Checking condition with above text is working fine, but if I try to check the values with array string it is not working properly. But text are similar any ideas?

Variable shortListed not holding array values, but strings. Remove quote ' around it :

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

Then you're able to accessing it by shortListed[0], shortListed[1], shortListed[n],..

More easy way to check array values contains something, i would like to use $.inArray() built in function in jQuery. As this function will return -1 if value did't not existed, otherwise will returned index if found that. See example below how to use that :

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

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM