Javascript多维数组打印单个字母

问题描述 投票:3回答:3

我在数组中有一个数组,并且某种程度上它无法将不同的值识别为单独的值,因此,如果我尝试打印2 nd值,它将为我打印2 nd字母第一个值。

var name = ["John", "Alex"];
var food = ['pizza', 'banana', "cheese", ["bmw", "tesla"], name];
document.write(food[4][1]);

['bmw', 'tesla']数组工作正常,其名称数组表现得很奇怪。

food[4][0] outputs J (from John)

food[4][5] outputs A (from Alex).
javascript arrays multidimensional-array
3个回答
6
投票

取决于您在何处运行var name = ["John", "Alex"];语句。

如果将其放入函数中,则它将按预期工作。

但是,如果您在浏览器的控制台中运行它,那么它将在全局范围内执行。在global scope中声明的变量是properties of the global window对象。但是window对象已经具有一个名为window的属性,并且其类型无法更改。如果为其分配的值不是字符串,则为name

这就是为什么声明:

its method toString() is used to convert it to a string

toString()分配一个新值,由于无法更改其类型,因此将数组var name = ["John", "Alex"]; 转换为字符串window.name并分配给["John", "Alex"]

对变量使用不同的名称("John,Alex",例如),即使在全局环境中,它也将按您期望的方式工作。


3
投票

您还应避免使用JavaScript内置对象,属性和方法的名称:

据我所知,您应该避免使用window.name关键字,因为它是保留的。尝试使用names应该可以。


-1
投票

那是因为food [4]不是数组而是字符串“ John,Alex”

name
© www.soinside.com 2019 - 2024. All rights reserved.