1
var leet = {
    h: 1,
    e: 2,
    r: 3,
    o: 4,
    l: 5
};

var s = "hello";
var fin = "";

for (var i in s) {
    if (leet.hasOwnProperty(i)) {
        fin + = leet[i];
    } else {
        fin + = i
    }
}
console.log(fin);

Why am I getting an error?

Awad Maharoof
  • 2,260
  • 1
  • 24
  • 36
user1223844
  • 87
  • 1
  • 2
  • 7

3 Answers3

0

Concatenation operator for object String is += not + =

For getting fin get value according to contents in s ypur code should be like this

for (var i in s) {
    if (leet.hasOwnProperty(s[i])) {
        fin += leet[s[i]];
    } 
}
999k
  • 6,257
  • 2
  • 29
  • 32
0

Your i value is 0,1,2,3,4 .. To get the char , you should use s[i] and string concat is += not + =

I mean

for (var i in s)
{
   alert(i);   // Gives 0,1,2,3,4
   alert(s[i]);  // Gives h,e,l,l,o
}

The below code gives you the expected result

var leet = {
        h: 1,
        e: 2,
        r: 3,
        o: 4,
        l: 5
    };

var s = "hello";
var fin = "";

for (var i in s) {
    if (leet.hasOwnProperty(s[i])) {
        fin += leet[s[i]];
    } else {
        fin += i
    }
}
alert(fin);

Working JS Fiddle

Prasath K
  • 4,950
  • 7
  • 23
  • 35
  • Click the link man and see the output.. Don't you have eyes ...?? Output for this code is 12554 .. Click http://jsfiddle.net/HCcC3/ – Prasath K May 08 '13 at 04:54
  • Great! Thats it! Thank you – user1223844 May 08 '13 at 04:57
  • @user1223844 same .. Me too don't know the reason for downvote.. Even now , you can accept it.. – Prasath K May 08 '13 at 04:58
  • @user1223844 Click the TICK symbol on the left side of my answer – Prasath K May 08 '13 at 05:02
  • 1
    I did not downvote, but the reason someone probably did is because of this popular thread: http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea ... In this case, I see no potential for error with its use, but if you choose to use this technique in a more complicated example, you could run into problems. Although you are only executing code on "has Own" properties, it's still looping over each property/method all the way up the prototype chain. A regular for(1 = 0; i < s.length; i++) loop is going to be more efficient & prevents potential errors. – 1nfiniti May 08 '13 at 05:10
  • @mikeyUX answering or pointing the drawback in an answer is good .. Good of you but why to downvote without saying reason ...?? And you know one user is giving downvote for all my answers now .. Just check my profile .. Don't know who that coward is ...!!! – Prasath K May 08 '13 at 05:14
  • @PrasathK Please read my comment again - i said i DID NOT downvote, but that drawback MAY be the reason why someone else did. – 1nfiniti May 08 '13 at 14:48
0

edit as fin += leet[i] and fin += i by removing the space within then now you can get your result as "01234"