简体   繁体   中英

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

This has been incredibly frustrating, especially given the simplicity of it. Simple 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]...).

Yet when I change it to document.write(name), it prints the whole array (ie "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. 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.

Using name in function scope scope will work fine of course.

You should use this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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