Heim  >  Artikel  >  Web-Frontend  >  js 排序动画模拟 冒泡排序_javascript技巧

js 排序动画模拟 冒泡排序_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:51:491105Durchsuche

而在某些场景中,队列确实像一支奇兵,可以带来不错的效果,比如配合定时器使用,可以模拟时间差效果

复制代码 代码如下:

function createDq(){
var dq = [], size = 0;
return {
setDq:function(queue){
dq = queue;
size = queue.length;
},
queue:function(fn){
size ++;
dq.push(fn);
},
dqueue:function(){
size --;
return dq.shift();
},
run:function(fn){
var me = this, timer;
timer = setInterval(function(){
if(size clearInterval(timer);
}
fn.call(null,me.dqueue());
},30);
}
}
}

以上是一个简单的实现,在不同的场景,可以做一些适当的变通,以做到因地制宜。
下面是一个模拟冒泡排序的动画,尝试着使用了一点点观察者模式,似乎还不错
复制代码 代码如下:

function bubble(){
var obs = [];
function compare(x, y) {
return x.w - y.w;
}
function swap(a, i, j) {
var t = a[i]; a[i] = a[j]; a[j] = t;
}
function proxy(a, i, j){
notify(a[i].id + "-" + a[j].id);
swap.apply(null,arguments);
}
function notify(arg){
obs[0].m.call(obs[0],arg);
}
return {
addOb:function(ob){
obs.push(ob);
},
sort:function(arr){
var len = arr.length;
for (var x = 1; x for (var y = 0; y if (compare(arr[y], arr[y + 1]) > 0) {
proxy(arr, y, y + 1);
}
}
}
}
}
}


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn