按属性值对对象排序 [英] Sorting objects by property values
本文介绍了按属性值对对象排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何仅使用Javascript实现以下方案:
How to implement the following scenario using Javascript only:
- 创建具有属性(最高速度,品牌等)的 car 对象
- 对这些属性订购的汽车列表进行排序
推荐答案
javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.
示例:
cars = [
{
name: "Honda",
speed: 80
},
{
name: "BMW",
speed: 180
},
{
name: "Trabi",
speed: 40
},
{
name: "Ferrari",
speed: 200
}
]
cars.sort(function(a, b) {
return a.speed - b.speed;
})
for(var i in cars)
document.writeln(cars[i].name) // Trabi Honda BMW Ferrari
好的,从您的评论中我看到您使用的"sort"一词含义不正确.在编程中,排序"是指按一定顺序放置事物",而不是按组排列事物".后者要简单得多-这就是您在现实世界中对事物进行分类"的方式
ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world
- 创建两个空数组(框")
- 对于列表中的每个对象,检查其是否符合条件
- 如果是,则将其放在第一个框"中
- 如果否,则将其放在第二个框"中
这篇关于按属性值对对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文