按属性值对对象进行排序 [英] Sorting objects by property values
本文介绍了按属性值对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何仅使用 Javascript 实现以下场景:
How to implement the following scenario using Javascript only:
- 创建一个具有属性(最高速度、品牌等)的汽车对象
- 对按这些属性排序的汽车列表进行排序
推荐答案
javascript 有 sort 函数可以将另一个函数作为参数 - 第二个函数用于比较两个元素.
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
好的,从你的评论中我看到你在错误的意义上使用了排序"这个词.在编程中,排序"的意思是按一定顺序排列",而不是按组排列".后者要简单得多——这就是你在现实世界中排序"事物的方式
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屋!
查看全文