javascript中声明变量名name(var name)被转成字符串的问题

chat

因为将变量命名为 name 产生了一个bug,害我找半天原因,
在浏览器控制台 声明一个名为name的数组,打印出来却是字符串:

var name =['1','2','3','4','5'];

name
"1,2,3,4,5"

查阅资料后了解到 name就是 window.name,用来表示 浏览器窗口的名称,window.name 会调用 toString 将赋给它的值转换成对应的字符串表示。

参考链接:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/name

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)

参考链接:https://stackoverflow.com/questions/31601839/why-does-arrays-stored-to-variable-name-in-chrome-convert-to-strings?tdsourcetag=s_pcqq_aiomsg

版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/955/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
javascript中声明变量名name(var name)被转成字符串的问题
javascript中声明变量名name(var name)被转成字符串的问题
<<上一篇
下一篇>>
chat