根据特定规则对对象进行排序 [英] Sorting objects according to a specific rule

查看:96
本文介绍了根据特定规则对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我需要根据类型对数组中的对象进行排序。每种类型都有更高的优先级,因此具有擦除类型的对象应具有最高优先级,因此位于数组的前面(index = 0)。

In Javascript I need to order objects in an array according to type. Each type has a higher priority, so an object with the type "wipe" should have the highest priority therefore be at the front of the array(index=0).

排序这些对象的最佳方法是什么?是否有内置函数可以执行此操作?

What would be the best way to sort these objects? Is there a builtin function that can do this?

例如:

function sortObjects( objs )
{
   // objs is an unsorted array of objects 
   var animPriority = {"wipe": 1, "fly": 2, "iris": 3, "flip": 4, "cube": 5, "blur": 6, "zoom": 7, "fade": 8, "glow": 9, "rotate": 10};

   for (var i=0; i<objs.length; i++)
       if (objs[i].type == "wipe")
          // bubblesort/bubbleswap element in objs[0] with objs[i]????
          // a bubble sort doesn't seem efficient though?
}


推荐答案

JavaScript的 array.sort 方法需要一个比较函数,只需传递这个函数:

JavaScript's array.sort method expects a compare function, simply pass this function:

function compareFunc(a,b) { return animPriority[a.type] - animPriority[b.type]; }

这篇关于根据特定规则对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆