Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying To Split Array Element By Space

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]);
like image 956
user7904332 Avatar asked Dec 07 '22 18:12

user7904332


2 Answers

  • 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

like image 135
Webeng Avatar answered Dec 10 '22 08:12

Webeng


"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]);
like image 40
anonman Avatar answered Dec 10 '22 07:12

anonman