【问题标题】:What does [ ] stand for? [duplicate][ ] 代表什么? [复制]
【发布时间】:2016-05-02 04:12:12
【问题描述】:

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

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

[] 是“对数据值进行排序,然后创建同名数组”的简写吗?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

[] 只是数组文字。这是一个空数组,因为它不包含任何元素。在这种情况下,它是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
  )

假设你有一个类似数组的对象,像这样:

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 通常比使用数组字面量更好,因为它更明确。

另见:

【讨论】:

    猜你喜欢
    • 2011-07-10
    • 2016-12-25
    • 2010-11-29
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多