What does [] mean?

I found this piece of code in StackOverflow:

[].sort.call(data, function (a, b) {})

Is it []short for "sort data values ​​and then create an array with the same name"?

+4
source share
1 answer

[]is just an array literal. This is an empty array because it does not contain any elements. In this context, this is a shortcut to Array.prototype.

This code basically allows you to use the method Array.prototype.sort()even for values ​​that are not arrays, for example arguments.

Further explanation:

[] // Array literal. Creates an empty array.
  .sort // Array.prototype.sort function.
  .call( // Function.prototype.call function
    data, // Context (this) passed to sort function
    function (a, b) {} // Sorting function
  )

Assuming you have an array-like object, for example:

var obj = {0: "b", 1: "c", 2: "a", length: 3};

, length. .sort() , Object.prototype . Array.prototype.sort() . Function.prototype.call(). .call() - , , - , . :

Array.prototype.sort.call(obj)

, Array.prototype.sort obj.

, Array.prototype , , .

. :

+13

Source: https://habr.com/ru/post/1625883/


All Articles