为什么数组存储为变量“名称”在Chrome中转换为字符串? [英] Why does arrays stored to variable "name" in Chrome convert to strings?

查看:133
本文介绍了为什么数组存储为变量“名称”在Chrome中转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome控制台中运行 var name = [1,2,3] 然后访问 name 我找回1,2,3。为什么会出现这种情况?



< img src =https://i.stack.imgur.com/SyLF3.pngalt =在这里输入图片描述>

解决方案

你看到的是一个全局变量,它是窗口对象的一部分。这实际上是浏览器使用的一个值,它反映了窗口的名称。 (请参阅文档



由于 window.name 是一个字符串getter / setter,因此您的数组将被转换为字符串。 (并且控制台在全局作用域中运行,所以 var name window.name 是相同的值。 (如果你嵌套在一个函数中,这种行为不适用,因为它不再是全局范围)

When I run var name = [1,2,3] in Chrome's console and then access the value of name I get back "1,2,3". Why is this the case?

解决方案

What you are seeing is a global variable that is part of the window object. This is actually a value the browser uses that reflects the name of the window. (see documentation)

Since window.name is a string getter/setter, your array is being cast to a string. (and the console operates in the "global scope", so var name and window.name are the same value. (if you were nested inside a function, this same behavior would not apply because it wouldn't be the global scope anymore)

这篇关于为什么数组存储为变量“名称”在Chrome中转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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