Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript排序回调_Javascript_Sorting - Fatal编程技术网

Javascript排序回调

Javascript排序回调,javascript,sorting,Javascript,Sorting,我需要对一大串Javascript项目进行排序,我正在使用sort函数,如下所示: var sorted_list = non_sorted.sort(function(a,b){ // Sort stuff here }); 我想做的是在sort函数完成后调用一个函数 当sort结束时,是否可以添加回调函数进行排序或触发事件?排序函数是同步的,因此您可以在调用后立即执行操作,但如果需要其他方法: Array.prototype.sortCallback = function(compareF

我需要对一大串Javascript项目进行排序,我正在使用
sort
函数,如下所示:

var sorted_list = non_sorted.sort(function(a,b){
// Sort stuff here
});
我想做的是在
sort
函数完成后调用一个函数


sort
结束时,是否可以添加回调函数进行排序或触发事件?

排序函数是同步的,因此您可以在调用后立即执行操作,但如果需要其他方法:

Array.prototype.sortCallback = function(compareFunction, resultFunction){
    result = this.sort(compareFunction);
    resultFunction(result);
}
用法:

non_sorted.sortCallback(function(a, b) {
  // Sort stuff here
}, function(sorted) {
   // Do something with the sorted array
});

你把它复杂化了。
sort
方法不是异步的,因此不需要回调或事件。只需将代码放在调用排序的代码后面即可:

var sorted_list = non_sorted.sort(function(a,b){
  // comparer
});
// The code just continues here after the sort

这有点脏,但它可以工作:

对于排序功能来说,速度足够慢(在合理范围内),并且比肉眼快

function sort_with_callback() {

            run_sort_function();

            setTimeout(function() { run_callback()},  3);}

您可以在对列表排序后添加要调用的函数。
.sort()
是同步的。按照建议,您可以执行
arr.sort(comparefn).arrMethod()
someFn(arr.sort(comparefn))因为排序返回了已排序的对象。@ EpasCalLo只是为了它的地狱:P和I认为我将使它成为一个原型来显示如何做到这一点。考虑用代码< >结果函数替换<代码>结果函数(结果)< /代码>。应用(结果,参数)< /C> >以允许参数传递到ReultFuffic。但是扩展内置功能不是一个好主意。