为什么不``} .toString.apply(array)`工作? [英] Why doesn't `{}.toString.apply(array)` work?
本文介绍了为什么不``} .toString.apply(array)`工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,当我想检查对象的类型(无论是数组,NodeList还是其他)时,我使用以下内容:
Usually, when I want to check the type of an object (whether it's an array, a NodeList, or whatever), I use the following:
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
所以...我很困惑。
推荐答案
当您使用 {
开始一行时,JavaScript认为它启动了一个块语句,而不是一个对象文字。将它括起来,你就可以了。
When you begin a line with {
JavaScript thinks it starts a block statement, not an object literal. Parenthesize it and you will be okay.
这篇关于为什么不``} .toString.apply(array)`工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文