按对象属性排序的Javascript对象列表 [英] Javascript object list sorting by object property

查看:125
本文介绍了按对象属性排序的Javascript对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这样做:

(抱歉不是javascript语法 - 仍在学习对象语言:))

(sorry not in javascript syntax-still learning object language :) )

object = car

object=car

attibutes:top-speed,brand ....

attibutes:top-speed, brand....

现在我想要通过最高速度,品牌排序这些汽车的列表...

now I want to sort the list of those cars in order by top-speed, brand...

我该怎么做(请注意解决方案必须只是javascript,没有php或其他东西)?

How do I do this (please note the solution must be javascript only, no php or other stuff) ?

推荐答案

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


  • 制作两个空数组(方框)

  • 列表中的每个对象,检查它是否符合条件

  • 如果是,请将其放在第一个框中

  • 如果没有,请把它放在第二个方框中

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"

这篇关于按对象属性排序的Javascript对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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