Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird thing happens with array

I'm playing around on codepen.io but for some reason my code is not working as expected:

var name = ["one",'two','three'];
$('body').append('<p>'+ name[0] + '</p>');

That code is appending the letter "o" to the page. When I switch the code to:

var person = ["one",'two','three'];
$('body').append('<p>'+ person[0] + '</p>');

"one" is appended to the page. Anybody know what's going on?

Here is the example: http://codepen.io/ntibbs/pen/ZbPPBm

like image 749
Nicholas Tibbs Avatar asked Nov 30 '25 03:11

Nicholas Tibbs


1 Answers

You appear to be in the global scope, so when you declare your name variable, you're clashing with the global window.name property.

This property has to be a string, so whenever you assign anything to it, it is coerced to a string.

When ["one",'two','three'] is coerced to a string, it first performs an Array.join, and you end up with "one,two,three", which is assigned to name. name[0] gives you the first character of that, "o".

Using the different variable name, person, you don't see this issue because you're not fighting the window property.

like image 53
James Thorpe Avatar answered Dec 02 '25 18:12

James Thorpe