[]代表什么?

Jan*_*ski 4 javascript arrays

我在StackOverflow上找到了这段代码:

[].sort.call(data, function (a, b) {})
Run Code Online (Sandbox Code Playgroud)

是[]"对数据值进行排序然后创建具有相同名称的数组"的简写吗?

Mic*_*ski 13

[]只是数组文字.它是一个空数组,因为它不包含任何元素.在这种情况下,它是一个快捷方式Array.prototype.

例如,此代码基本上允许您Array.prototype.sort()在非数组的值上使用方法arguments.

进一步说明:

[] // 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
  )
Run Code Online (Sandbox Code Playgroud)

假设你有一个类似数组的对象,如下所示:

var obj = {0: "b", 1: "c", 2: "a", length: 3};
Run Code Online (Sandbox Code Playgroud)

它是类似数组的,因为它有数字键和length属性.但是,你不能只调用.sort()它的方法,因为Object.prototype没有这样的方法.您可以Array.prototype.sort()在对象的上下文中调用.这正是Function.prototype.call()方法的用途..call()方法的第一个参数是传递给函数的上下文,其余的是传递给函数的参数.例如:

Array.prototype.sort.call(obj)
Run Code Online (Sandbox Code Playgroud)

返回已排序的对象,因为Array.prototype.sort它的行为类似于obj方法.

请注意,使用Array.prototype通常比使用数组文字更好,因为它更明确.

也可以看看: