简体   繁体   English

为什么 `{}.toString.apply(array)` 不起作用?

[英]Why doesn't `{}.toString.apply(array)` work?

Usually, when I want to check the type of an object (whether it's an array, a NodeList, or whatever), I use the following:通常,当我想检查 object 的类型时(无论是数组、NodeList 还是其他),我使用以下代码:

var arr = [] // I don't do this, but it's for the sake of the example
var obj = {}
obj.toString.apply(arr) // This works

The question is: why can I not do the following?问题是:为什么我不能执行以下操作?

var arr = []
{}.toString.apply(arr) // Syntax error: Unexpected token .

I don't get where the syntax error is.我不知道语法错误在哪里。

I can do something approaching with [] though, the following works:我可以用[]做一些接近的事情,以下工作:

var nodeList = document.getElementsByClassName('foo')
[].forEach.call(nodeList, function(bar) { console.log(bar) }) // Works

So... I'm confused.所以...我很困惑。

When you begin a line with { JavaScript thinks it starts a block statement, not an object literal.当您以{ JavaScript 开始一行时,认为它开始了一个块语句,而不是 object 文字。 Parenthesize it and you will be okay.括号它,你会没事的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM