6

我是一个 javascript 新手,这是来自 ExtJS 的代码,这让我感到困惑:

supportsSort = (function() {
    var a = [1,2,3,4,5].sort(function(){ return 0; });
    return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
}()),

有人能告诉我为什么 ExtJS 要做这个测试吗?

最好附上一些示例代码。

4

2 回答 2

2

Hesitant to post this as the answer as I'm admittedly just taking an educated guess but according to MDN, the browser-compatibility for Array.sort is listed as ECMAScript5 and "yes" for everything (as opposed to listing actual version numbers) - leaving a test for actual support more or less redundant.

The variable name is probably a little bit miss-leading though because if you actually follow what it's doing, the function that is passed to sort is just returning 0; typically you might return 1 or -1 depending on your comparison conditions in order to manipulate the order of the array - so by doing this the expected result is that the order of the array remains unchanged.

The return statement is just a chain of boolean checks as to whether the array is still in the same order as it was initially. Arguably then this supportsSort flag is there to check whether or not the browser/Javascript's implementation of the sort function is in fact a stable algorithm.

于 2013-09-14T18:48:00.157 回答
0

我认为需要进行此测试以检查浏览器是否支持此功能。

正如本文或此链接中讨论那样,您可以找到. 显示并非所有浏览器版本都支持排序功能。Array.prototype.sort([comparator])

这些天没有不支持此功能的浏览器(我说的是最新版本)。但是,如果 Ext Js 用于为早期版本进行开发,则需要它。

于 2013-09-15T06:25:16.733 回答