为什么JavaScript split()会使用不同的变量名生成不同的输出? [英] Why does JavaScript split() produce different output with different variable names?

查看:61
本文介绍了为什么JavaScript split()会使用不同的变量名生成不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是Chrome开发者控制台的一些代码和输出

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

案例1:

var myarr = document.location.hostname.split(".");    //typed
undefined                                             //output
myarr[0]                                              //typed
"ptamz"                                               //output: ONE

案例2:

var name = document.location.hostname.split(".");     //typed
undefined                                             //output
name[0]                                               //typed
"p"                                                   //output: TWO

为什么两个输出(注释输出:ONE和输出:TWO)不同?

Why are the two outputs (commented Output: ONE, and Output: TWO) different?

屏幕截图:

推荐答案

name window 的属性。看来,当您尝试将该属性设置为数组时,键将以逗号连接(调用 toString )。所以你实际上是将 window.name 属性设置为 document.location.hostname.split(。)的每个元素的串联,以逗号分隔。

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.

这是我的Chrome控制台的屏幕截图,展示了会发生什么:

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

原因 name [0] 然后结果 p 是你可以使用方括号访问字符串的字符:

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"

修改

正如其他人所提到的,这只是全球范围内的情况。您可以在后代范围内声明名为 name 的变量。虽然,在这种情况下,省略 var 关键字仍会导致您访问 window.name

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"]
}

这篇关于为什么JavaScript split()会使用不同的变量名生成不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆