我应该如何在jQuery中使用.sort()? [英] How should I use .sort() in jQuery?
问题描述
我一直在看很多人在jQuery中使用 .sort()
函数的例子。
I've been looking at a lot of examples where people use the .sort()
function in jQuery.
例如:
$('#myId').sort(..);
我找不到 sort()$ c $的任何文档c>在jQuery API中,有人可以告诉我它的用法吗?
By I cannot find any documentation for sort()
in the jQuery API, can anyone show me its usage?
推荐答案
因为它不是jQuery(官方)的一部分,但是是代理的 Array.sort 。
Because it's not part of jQuery (officially), but is a proxied Array.sort.
正如Derek指出的那样, jQuery(...)
不返回数组。相反,jQuery 添加代理以使jQuery对象行动像一个数组:
As Derek points out, jQuery(...)
does not return an array. Rather, jQuery adds a proxy to make the jQuery object "act like an array":
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort, // <-- here
splice: [].splice
此代理有效,因为函数中的 this
由调用该函数的对象决定。而且, Array.sort
(和 Array.splice
)可以在任何这个
这是数组之类的(有一个长度
,大概是属性 0..length-1
)。以下是使用 Array.sort
的自定义对象[ab]的示例:
This proxy works because the this
in a function is determined by the object on which the function was invoked. And, furthermore, Array.sort
(and Array.splice
) work on any this
that is "array like" (has a length
and presumably properties 0..length-1
). Here is an example of a custom object [ab]using Array.sort
:
var a = {0: "z", 1: "a", length: 2, sort: [].sort}
a[0] // -> "z"
a.sort() // in-place modification, this === a
a[0] // -> "a"
a instanceof Array // -> false (never was, never will be Array)
YMMV跟随仅供内部使用注释。
YMMV following the "For internal use only" notes.
这篇关于我应该如何在jQuery中使用.sort()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!