定义数组时:
var name = ['A', 'B', 'C'];
并将其显示在控制台上:
console.log(name);
我们得到一个字符串!
"A,B,C"
但是当用另一个名称定义数组时:
var haha = ['A', 'B', 'C'];
当显示“它应该做什么”时,我们得到一个数组!
(3) ["A", "B", "C"]
0: "A"
1: "B"
2: "C"
length: 3
__proto__: Array(0)
为什么会发生这种情况?
最佳答案
name
是一个全局属性,是 window
的一部分。目的。它有一个特殊的属性,可以通过调用 .toString()
方法将其值转换为字符串:
window.name
will convert all values to their string representations by using the toString method.- MDN
因此,当您将全局变量设置为 var name
时,您就是在窗口上设置全局变量 name
,该窗口会将数组转换为字符串。您可以使用 let
或 const
不将其添加到 window
中,从而将其保留为数组:
const name = [1, 2, 3];
console.log(name);
关于javascript - 为什么 JavaScript 将名为 "name"的数组解析为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60068204/