简体   繁体   English

无法将数组分配给全局变量“名称”

[英]Can't assign an array to the global variable "name"

This has been incredibly frustrating, especially given the simplicity of it.这令人难以置信地令人沮丧,尤其是考虑到它的简单性。 Simple javascript:简单的javascript:

<script type="text/javascript">

var name = new Array("cat","dog");

document.write(name[1]);

</script>

This script prints: "a" (as in the "a" from "cat"...aka name[0][1]...).此脚本打印:“a”(如“cat”中的“a”...又名 name[0][1]...)。

Yet when I change it to document.write(name), it prints the whole array (ie "cat,dog").然而,当我将其更改为 document.write(name) 时,它会打印整个数组(即“cat,dog”)。 Why for the love of god is this simple array failing to print the entire string (which should be "dog")?!为什么上帝的爱是这个简单的数组无法打印整个字符串(应该是“狗”)?!

The global variable name refers to the existing window.name property, which was used to set the name of the browser window.全局变量name是指现有的window.name属性,该属性用于设置浏览器窗口的名称。 It converts any value assigned to it to a string:它将分配给它的任何值转换为字符串:

 window.name = [1, 2, 3]; console.log(typeof window.name, window.name);

If you change the variable name to eg names it will do as expected.如果您将变量名称更改为例如names ,它将按预期执行。

Using name in function scope scope will work fine of course.当然,在函数作用域范围内使用name可以正常工作。

You should use this instead:你应该改用这个:

var name = ["cat", "dog"];
document.write(name[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM