var name在Javascript中产生奇怪的结果 [英] var name produces strange result in Javascript

查看:145
本文介绍了var name在Javascript中产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这段代码:

var name = ["Apples","Oranges","Strawberries"];
console.log(name.length);

此代码产生了这个奇怪的结果27 !!问题似乎是使用变量名称作为名称,它看起来像一个保留关键字。

This code produces this weird result of 27 !! The issue seems to be with using the variable name as 'name' which seems like a reserved keyword.

但任何人都可以解释为什么这种奇怪的行为?

But can anyone explain why this weird behavior ?

推荐答案

它指的是 window.name ,这是其名称窗口。

It refers to window.name, which is the name of the window.

您可以使用窗口的名称来定位超链接,但它通常不常用。

You can use the window's name to target hyperlinks, but it's not typically useful.

更多关于 window.name 的信息: https://developer.mozilla.org/en-US/docs/Web/API/Window.name

只需测试Chrome :
你不能阻止 var name 来自 window.name ,这是一个字符串。无论您将值设置为什么,它都将被转换为字符串,以便它是一个有效的窗口名称。因此, name.length 是字符串中的字符数。最好避免变数或者对它们非常小心!

Just testing in chrome: You can't stop var name from being window.name, which is a string. No matter what you set the value to, it will be cast as a string so that it is a valid window name. So, name.length is the amount of characters in the string. It's best to avoid variable or be very careful about them!

正如我从其他一些评论中看到的那样,如果你是新手,这是一个奇怪的概念。关注的是 window.name 所指的内容。 window.name 窗口的名称。任何使用它都会命名窗口。

As I can see from some of the other comments, this is an odd concept if you're new to it. The concern is over what window.name refers to. window.name is the name of the window. Any use of it is naming the window.

捍卫Chrome的行为是合乎逻辑的:

如果这个 var document ='foo'做了它会做的事情,你就会覆盖 window.document - 文档对象 - 带有字符串。那将是一个很大的问题。 name window 的属性,就像 document 一样不应该(并且不能在Chrome中)替换的用途。

If this var document = 'foo' did what it looks like it would do, you would have overwritten window.document - the document object - with a string. That would be quite the problem. name is a property of window just like document and has a use that shouldn't be (and can't be in Chrome) replaced.

这篇关于var name在Javascript中产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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