javascript - How come js array loop outputs commas? . .
習慣沉默
習慣沉默 2017-05-18 10:56:27
0
6
793

Just like the title. . . Find out why

習慣沉默
習慣沉默

reply all(6)
Ty80

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.

为情所困

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 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]
})()

Or use the ES6let keyword to define variables

仅有的幸福

Because 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!