Search code examples
javascriptinternet-explorer-11

eval() not working while object iteration


I am trying to execute the following code snippet..

var sUserID = "HELLO".toUpperCase();
                var oAlphabets = {
                    "A": 1,
                    "B": 2,
                    "C": 3,
                    "D": 4,
                    "E": 5,
                    "F": 6,
                    "G": 7,
                    "H": 8,
                    "I": 9,
                    "J": 10,
                    "K": 11,
                    "L": 12,
                    "M": 13,
                    "N": 14,
                    "O": 15,
                    "P": 16,
                    "Q": 17,
                    "R": 18,
                    "S": 19,
                    "T": 20,
                    "U": 21,
                    "V": 22,
                    "W": 23,
                    "X": 24,
                    "Y": 25,
                    "Z": 26
                };
                var iEncoded = 0, sEncoded;
                for (var i in sUserID) {
                    var sEval = "oAlphabets."+sUserID[i];
                    iEncoded = iEncoded + eval(sEval);
                }
                if(iEncoded <100){
                    sEncoded = "0"+iEncoded;
                }
                else{
                    sEncoded = ""+iEncoded;
                }

It works as expected in Chrome and returned the result 078. However, it gave the error "Expected ;" in IE 11.

What is the issue here and how to get rid of it..

Regards,

Fahad Hamsa


Solution

  • There is Zero reason to use eval. Just use bracket notation like it is meant to be used with variables.

    iEncoded += oAlphabets[sUserID[i]];