Attempt to divide an element of an array by space

I am confused why this code causes the name [0] to be "f" instead of "foo". I thought that when I pass the "separation method", foo will be the result.

var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";

var name = ar[0].split(' ');
console.log(name[0]);
Run codeHide result
+4
source share
4 answers
  • The variable is namereserved in browsers. If you must enter the developer console (click f12) and enter window.name, you will see that it either gives you ""or some other string result.

  • The previous code ar[0].split(' ');will return the following array:

    [
       "foo",
       "bar"
    ]
    
  • , , typeof ;), "foo,bar". .

  • name[0] "foo,bar" , f

+4

"name" window.name .   .

, ​​ array2

var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";

var name2 = ar[0].split(' ');
console.log(name2[0]);
+4

name , , JavaScript. name - , belopw.

var name = ar[0].split(' '); .

var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";

var changeThisVariableName = ar[0].split(' ');  
console.log(changeThisVariableName[0]);
Hide result
+3

Wrap it in a function, you will get exactly the result, because the name refers to window.name

(function () {
    var ar = [];
    ar[0] = "foo bar";
    ar[1] = "dumdumdum";

    var name = ar[0].split(' ');
    console.log(name[0]);
})()
+3
source

Source: https://habr.com/ru/post/1675391/


All Articles