I am confused why this code results with name[0] being equal to "f" instead of "foo". I thought that when I passed ' ' to the split method "foo" would be the result.
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name = ar[0].split(' ');
console.log(name[0]);
The variable name
is reserved in browsers. If you were to go in the developer console (click f12), and type window.name
, you would see that it either gives you ""
or some other string result.
Your previous code ar[0].split(' ');
is going to return the following array:
[
"foo",
"bar"
]
but the browser forcibly converts it to a string because your browser is mad at you since you are trying to change the typeof
of its reserved variable ;), hence the string value "foo,bar"
. You might however get different results on different browsers.
And doing name[0]
to a string value of "foo,bar"
gets the first letter of the string, f
"name" refers to window.name and is in use. so your array becomes a string.
Use another variable such as array2
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name2 = ar[0].split(' ');
console.log(name2[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With