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?

asked Jul 12, 2012 at 16:51
3
  • 3
    Have you tried using typeof? Commented Jul 12, 2012 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. Commented Jul 12, 2012 at 16:58
  • I think of Array as Object, but with special treatment to keys that only contains non-negative numbers. Commented Jul 12, 2012 at 16:59

1 Answer 1

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

answered Jul 12, 2012 at 16:56
Sign up to request clarification or add additional context in comments.

1 Comment

So using parseInt sounds rather stupid. I have updated my answer on the other post. Thanks... learning everyday.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.