简体   繁体   English

函数中的方括号是什么意思?

[英]What do empty brackets inside a function mean?

I came across the following code and I'm curious what the [] means: 我遇到了以下代码,我很好奇[]含义:

function checkForImage(mutation) {
        if (mutation.addedNodes && (mutation.addedNodes.length > 0)) {
            [].slice.call(mutation.addedNodes).forEach(function(node) { ...

The purpose is just to get an array ( [] is an array) in order to be able to get the slice function. 目的只是为了获得一个数组( []是一个数组)以便能够获得slice函数。

This is necessary because mutation.addedNodes is probably "array-like" : array functions work but it's not an instance of Array . 这是必需的,因为mutation.addedNodes可能类似于“数组”:数组函数可以工作,但它不是Array的实例。 Here this construct with slice makes an array (so that the forEach function is available). 在这里,此带有slice构造构成一个数组(以便forEach函数可用)。 This construct is common for example for live node lists. 例如,此结构在活动节点列表中很常见。 You can test it in the console on this page : 您可以在此页面上的控制台中对其进行测试:

document.getElementsByTagName('img').constructor // -> NodeList
document.getElementsByTagName('img').forEach // -> undefined
[].slice.call(document.getElementsByTagName('img')).constructor // -> Array
[].slice.call(document.getElementsByTagName('img')).forEach // -> a function

It could also have been 也可能是

Array.prototype.slice.call(mutation.addedNodes).forEach(function(node) {

which would have avoided the creation of a useless instance (whose cost is probably ridiculously low) but would have been more verbose. 这样可以避免创建无用的实例(其成本可能非常低),但是会更加冗长。

But a simpler and cleaner solution could have been 但是更简单,更清洁的解决方案本来是

[].forEach.call(mutation.addedNodes, function(node) {

unless some hidden code justifies the use of a real array. 除非某些隐藏代码证明使用实数组是合理的。

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

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