[removed] Quickly lookup value in object (like we can with properties)

后端 未结 4 551
名媛妹妹
名媛妹妹 2021-01-05 14:07

I have an object that has pairs of replacement values used for simple encoding / decoding (not for security, just for a convenience; too complicated to explain it all here).

4条回答
  •  长情又很酷
    2021-01-05 14:36

    A reverse encoder would make more sense, but you can write a replace function without all the hasOwnProperty etc.tests.

    var str= 'Hello World!',
    obj={
        's':'d',
        'm':'e',
        'e':'h',
        'x':'l',
        'z':'o',
        'i':'r',
        'a':'w',
        'o':'!',
        '-':' '
    }
    str= str.replace(/./g, function(w){
        for(var p in obj){
            if(obj[p]=== w) return p;
            if(obj[p]=== w.toLowerCase()) return p.toUpperCase();
        };
        return w;
    });
    

    returned value: (String) Emxxz-Azixso

提交回复
热议问题