Why does JavaScript split() produce different output with different variable names?

后端 未结 3 1743
陌清茗
陌清茗 2021-01-18 05:38

Following is some codes and output from the Chrome Developers\' Console

Case 1:

var myarr = document.location.hostname.split(\".\");         


        
3条回答
  •  感动是毒
    2021-01-18 06:12

    name is a property of window. It appears that when you try to set that property to an array, the keys are joined with a comma (the result of calling toString on an array). So you are actually setting the window.name property to the concatenation of each element of document.location.hostname.split("."), separated by commas.

    Here's a screenshot from my Chrome console demonstrating what happens:

    enter image description here

    The reason name[0] then results in p is that you can access the characters of strings using square brackets:

    name = "hello,world";
    console.log(name[0]); //"h"
    

    Edit

    As others have mentioned, this will only be the case in the global scope. You are free to declare a variable named name inside a descendant scope. Although, obviously, omitting the var keyword in this case would still result in you accessing window.name:

    function example() {
        var name = ["hello", "world"];
        console.log(name); //["hello", "world"]
    }
    

提交回复
热议问题