无法将数组分配给全局变量“名称"; [英] Can't assign an array to the global variable "name"

查看:37
本文介绍了无法将数组分配给全局变量“名称";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这令人非常沮丧,尤其是考虑到它的简单性.简单的javascript:

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>

此脚本打印:a"(如cat"中的a"...又名 name[0][1]...).

This script prints: "a" (as in the "a" from "cat"...aka name[0][1]...).

然而,当我将其更改为 document.write(name) 时,它会打印整个数组(即cat,dog").天啊,为什么这个简单的数组没有打印出整个字符串(应该是狗")?!

Yet when I change it to document.write(name), it prints the whole array (i.e. "cat,dog"). Why for the love of god is this simple array failing to print the entire string (which should be "dog")?!

推荐答案

全局变量 name 指的是现有的 window.name 属性,用于设置浏览器窗口的名称.它将分配给它的任何值转换为字符串:

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);

如果您将变量名称更改为例如names 它将按预期执行.

If you change the variable name to e.g. names it will do as expected.

在函数作用域中使用 name 当然可以正常工作.

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

这篇关于无法将数组分配给全局变量“名称";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆