简体   繁体   中英

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.

This is necessary because mutation.addedNodes is probably "array-like" : array functions work but it's not an instance of Array . Here this construct with slice makes an array (so that the forEach function is available). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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