开发者

javascript - coldfusion - working with a list

This is probabl开发者_开发百科y easy for someone.

I am returning a list of campaignIDs (12,45,66) via JSON to a javascript variable

var campaignList = res.DATA.CAMPAIGNS

Now, given a specified campaignID passed in the URL

var campaignId ='<cfoutput>#url.campaignID#</cfoutput>'

I want to check if the returned list contains this campaignID

Any help much appreciated.


Plenty of ways to do it, but I like nice data structures, so ...

Split the list on comma, then loop over list, looking for value:

function campaignExists(campaignList,campaignId) {
    aCampaignList = campaignList.split(',');
    for (i=0;i<aCampaignList.length;i++) {
        if (aCampaignList[i]==campaignId)
            return true;
    }
    return false;
}


Since Array.indexOf sadly isn't cross browser, you're looking at something like:

// assume there is no match
var match_found = false;

// iterate over the campaign list looking for a match,
// set "match_found" to true if we find one
for (var i = 0; i < campaignList.length; i += 1) {
    if (parseInt(campaignList[i]) === parseInt(campaignId)) {
        match_found = true;
        break;
    }
}

If you need to do this repeatedly, wrap it in a function


Here's a bit of a "out of the box" solution. You could create a struct for your property id's that you pass into the json searilizer have the key and the value the same. Then you can test the struct for hasOwnProperty. For example:

var campaignIDs = {12 : 12, 45 : 45, 66 : 66};

campaignIDs.hasOwnProperty("12"); //true
campaignIDs.hasOwnProperty("32"); //false

This way if the list is pretty long you wont have to loop through all of the potential properties to find a match. Here's a fiddle to see it in action:

http://jsfiddle.net/bittersweetryan/NeLfk/


I don't like Billy's answer to this, variables within the function have been declared in the global scope and it is somewhat over complicated. If you have a list of ids as a string in your js just search for the id you have from user input.

var patt = new RegExp("(^|,)" + campaignId + "(,|$)");
var foundCampaign = campaignList.search(patt) != -1;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜