我很困惑为什么这段代码的结果是name [0]等于"f"而不是"foo"。我以为当我将' '传递给split方法时,"foo"将是结果。
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name = ar[0].split(' ');
console.log(name[0]);
我很困惑为什么这段代码的结果是name [0]等于"f"而不是"foo"。我以为当我将' '传递给split方法时,"foo"将是结果。
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
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name2 = ar[0].split(' ');
console.log(name2[0]);
在编写代码时,应避免使用 name
作为变量名,因为它是现有的 JavaScript 内置对象、属性和方法。请将变量名 name
改为其他名称后,确保您的代码仍然能够正常工作,检查下面的代码。
你的 var name = ar[0].split(' ');
返回一个子字符串数组。
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var changeThisVariableName = ar[0].split(' ');
console.log(changeThisVariableName[0]);
.split()
总是返回一个数组。 - nnnnnn.split()
一个数组。底线是这里的问题与.split()
无关,而与您是否可以有一个名为name
的全局变量有关... - nnnnnnname
变量被保留了?因为如果你将该变量重命名为其他任何名称,那么这段代码应该可以工作。 - cosmoonot将其包装在一个函数中,您将获得确切的结果,因为名称指的是window.name
(function () {
var ar = [];
ar[0] = "foo bar";
ar[1] = "dumdumdum";
var name = ar[0].split(' ');
console.log(name[0]);
})()
name
之外的其他变量名。或者将代码放在函数内,使name
成为局部变量。存在一个内置的全局window.name
属性,它始终是一个字符串,而你的name
引用了该属性,因此你的数组被转换为字符串,然后name[0]
获取该字符串的第一个字符。另请参见 此问题。 - nnnnnn