javascript的取最值和排序

数据的存储方式很多情况是Array和对象数组等,通常也会做到一些排序求最值的问题。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
        var ages = [90,91,56,99,70,88,87,100,111];
        var names = ["martin","france","acton","sarah","ably","abby","alisa","alice"];
        var persons = [
            {hair:"gray",name:"mimi",high:"170cm",age:"99"},
            {hair:"white",name:"martin",high:"170cm",age:"55"},
            {hair:"red",name:"marven",high:"170cm",age:"66"},
            {hair:"blue",name:"france",high:"170cm",age:"77"},
            {hair:"golden",name:"acton",high:"170cm",age:"88"},
            {hair:"align",name:"mimi",high:"170cm",age:"99"}
        ];

        //method one : get the max number of array ages
       var num = ages[0];
       for(var i=0;i<ages.length;i++){
           for(var j=i+1;j<ages.length;j++){
               if(num < ages[j]){
                   num = ages[j];
               }
           }
       }

        //method two : invoke the sort method and add a function sortNumber
        function sortNumber(a,b){
            return a - b;
        }
        ages.sort(sortNumber);
        min = ages[0];
        max = ages[ages.length-1];

        //sort by the alpha
        names.sort();

        //sort the object array by it's age property
        function compare(a,b){
            if(a.age > b.age){
                return 1;
            }
            if(a.age < b.age){
                return -1;
            }
            return 0;
        }
        persons.sort(compare);

    </script>

</body>
</html>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值