如何解释(文件)0 []

时间:2015-11-12 09:24:20

标签: javascript

我看到了这样的代码片段:

with(document)0[(getElementsByTagName('head')[0] || body).appendChild(createElement(xxx))]

我不知道如何理解with(document)0[]

2 个答案:

答案 0 :(得分:0)

这不是有效的JavaScript语法,并试图解读它,语义非常不清楚。

我想作者的意思是这样的:

document.getElementsByTagName('head')[0] || document.body.appendChild(createElement(xxx))

&#34;如果文档中有任何<head>标记,则返回第一个。否则返回将createElement(xxx)附加到正文&#34;。

的结果

答案 1 :(得分:0)

It is hard to answer this question without the full code. But I'll made some assumptions here.

The first thing that I'd like to say is to avoid of using with() statement. It is not recommended in ECMAScript 5 and is forbidden in strict mode. And one of the reasons is your fragment - this code confused a lot of people, even you.

So let's rewrite it a little bit to make it more understandable:

with(document) {
    0[(getElementsByTagName('head')[0] || body).appendChild(createElement(xxx))];
}

How with works you can read here - with statement, but basically it is give us an ability to use directly all the properties and methods of the expression that we are sending to with (in our case it's a document).

So, how this code fragment will looks like without with?

0[(document.getElementsByTagName('head')[0] || document.body).appendChild(document.createElement(xxx))];

The only answer that I don't have is - why to execute this code inside of brackets? The assumption that I have is the following:

this code fragment (document.getElementsByTagName('head')[0] || document.body).appendChild(document.createElement(xxx)) will return the node of new created element. But if we place this code into the 0[], it will return undefined as there is no such property. Again, it's hard to understand all parts of this code fragment without the whole picture.