1

Yesterday I was answering a question on stackoverflow, and there's something I don't understand in my own answer...

References: the thread in question, and my fiddle

Here is the code from my answer:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function($0,$1){return params[parseInt($1)];});

Now, what surprises me is that the following code works too:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function($0,$1){return params[$1];});

My question: how come parseInt is not needed? At what point does JavaScript convert $1 into a number? Is it in the regex, or in the array?

Community
  • 1
  • 1
Christophe
  • 27,383
  • 28
  • 97
  • 140
  • 3
    Have you tried using [`typeof`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof)? – Wex Jul 12 '12 at 16:53
  • doh...no, I should have started there. I just tried and it says string. So it seems that for the array 1 and '1' are the same. – Christophe Jul 12 '12 at 16:58
  • I think of `Array` as `Object`, but with special treatment to keys that only contains non-negative numbers. – nhahtdh Jul 12 '12 at 16:59

1 Answers1

0

That is because javascript reads indexes as a string

array[1], will be converted to array['1'] before being read

The same way object['first'] will work

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • So using parseInt sounds rather stupid. I have updated my answer on the other post. Thanks... learning everyday. – Christophe Jul 12 '12 at 17:08