简体   繁体   中英

Matching a string to an array

I need your your help,

For some strange reason, when my var str is set to " OTHER-REQUEST-ASFA " the matched key comes back as " ASF " as opposed to " ASFA "

How can I get the returned output key of " ASFA " when my str is " OTHER-REQUEST-ASFA "

function test() {

    var str = "OTHER-REQUEST-ASFA"

    var filenames = {
        "OTHER-REQUEST-ASF": "ASF",
        "OTHER-REQUEST-ASFA": "ASFA",
        "OTHER-REQUEST-ASFB": "ASFB",
        "OTHER-REQUEST-ASFC": "ASFC",
        "OTHER-REQUEST-ASFE": "ASFE" 
    }

    for (var key in filenames) {
        if (str.indexOf(key) != -1) { alert(filenames[key]) }
    }

}

You could switch from

str.indexOf(key)

to

key.indexOf(str)

 function test() { var str = "OTHER-REQUEST-ASFA", filenames = { "OTHER-REQUEST-ASF": "ASF", "OTHER-REQUEST-ASFA": "ASFA", "OTHER-REQUEST-ASFB": "ASFB", "OTHER-REQUEST-ASFC": "ASFC", "OTHER-REQUEST-ASFE": "ASFE" }, key; for (key in filenames) { if (key.indexOf(str) != -1) { console.log(filenames[key]); } } } test(); 

To answer why it's not working as you want...

You've got:

str.indexOf(key)

This checks for the first instance of key in str .

So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA , so the condition is true.


However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ , the easiest way is to use split() :

str.split('-')[2]

will always return the last section after the last -

原因“ OTHER-REQUEST-ASFA”。indexOf(“ OTHER-REQUEST-ASF”)将不会返回-1,因此将显示“ ASF”

You can also use static method Object.keys() to abtain array of keys

 var test = () =>{ var str = "OTHER-REQUEST-ASFA" var filenames = { "OTHER-REQUEST-ASF": "ASF", "OTHER-REQUEST-ASFA": "ASFA", "OTHER-REQUEST-ASFB": "ASFB", "OTHER-REQUEST-ASFC": "ASFC", "OTHER-REQUEST-ASFE": "ASFE" } Object.keys(filenames).forEach(x => { if ( x.indexOf(str) !== -1) console.log(filenames[str]); }); } test(); 

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