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

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

问题描述

假设我们有这个代码段:

Lets say we have this code segment :

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 - 文档对象.那问题就大了.namewindow 的一个属性,就像 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天全站免登陆