search

Home  >  Q&A  >  body text

javascript - How come js array loop outputs commas? . .

Just like the title. . . Find out why

習慣沉默習慣沉默2807 days ago813

reply all(6)I'll reply

  • PHP中文网

    PHP中文网2017-05-18 10:58:27

    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.

    reply
    0
  • 为情所困

    为情所困2017-05-18 10:58:27

    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

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-18 10:58:27

    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

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-18 10:58:27

    Because the array is treated as a string when output directly on the console

    reply
    0
  • ringa_lee

    ringa_lee2017-05-18 10:58:27

    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

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-18 10:58:27

    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

    reply
    0
  • Cancelreply