The reason is namespecial, the browser is forced to convert it to string when assigning value.
var name = [0, 1, 2]
console.log(name) // 输出 "0,1,2"
Because window has built-in propertiesname,所以你在全局下声明name其实就是在给window.name赋值。关于window.name。类似的属性还有status, so when you declare name globally, you are actually assigning a value to window.name. About window.name. Similar attributes include status, etc.
So there is no problem if you use name1. In fact, if you use name in a non-global environment, or use name in a global environment of node, there is no comma.
Because your scope is global, so what you defined name 变量相当于 window.name 它是一个特殊的全局变量 任何值赋值给它都会进行 toString 操作 这里你将数组给 window.name Actually, if you can output it, you will find that it is not an array but a string And strings can be traversed using loops, so a comma is output
var name = [0, 1, 2]
console.log(name) // 0,1,2
console.log(typeof name === 'string') // true
Solution: Do not use global scope and add a layer of self-executing function
(function() {
var name = [0, 1, 2]
console.log(name) // [0, 1, 2]
console.log(Object.prototype.toString.call(name)) // [object Array]
})()
Because name is the attribute name of js and is a reserved field. When for in loops through this field, it is processed as a String, so every character in the String will be output
The reason is
name
special, the browser is forced to convert it to string when assigning value.Because window has built-in properties
name
,所以你在全局下声明name其实就是在给window.name赋值。关于window.name。类似的属性还有status
, so when you declare name globally, you are actually assigning a value to window.name. About window.name. Similar attributes includestatus
, etc.So there is no problem if you use
name1
. In fact, if you use name in a non-global environment, or use name in a global environment of node, there is no comma.Friends, name is a keyword, don’t use this to name variables.
You can typeof and you will find that name is string and name1 is object
Because your scope is global, so what you defined
name
变量相当于window.name
它是一个特殊的全局变量 任何值赋值给它都会进行
toString
操作这里你将数组给
window.name
Actually, if you can output it, you will find that it is not an array but a stringAnd strings can be traversed using loops, so a comma is output
Solution: Do not use global scope and add a layer of self-executing function
Or use the
ES6
的let
keyword to define variablesBecause the array is treated as a string when output directly on the console
I tried it and it seems to be a problem with the variable name. As long as it is name, every character will be output. The specific reason is unknown
Because name is the attribute name of js and is a reserved field. When for in loops through this field, it is processed as a String, so every character in the String will be output