Skip to content

JavaScript中最快方法查找最大值/最小值 #14

Description

@ychow

当我们想在一堆值里面找寻最大或者最小的那个值时,最简便的方法就是:

var min=Math.min(1,2,3,22,111);
var max=Math.max(1,2,3,22,111);

然而在实际业务场景中,一般比较的都是数组,而且会经常用到,这时候我们就可以给Array扩展一些方法,在需要用到的时候可以信手拈来。

Array.prototype.min=function(){
    var narray=[];
    for(var i=0;i<this.length;i++){
        if(typeof this[i] == 'number'){
            narray.push(this[i])
        }
    }
    return Math.min.apply(Array,narray)
}

var a=[2,333,'33aa',undefined,null,7777,333,222222];
a.min() //2

最大值的方法同理!

Ps:其实在apply的第一个参数这里你可以随便设置一个什么值(除特殊符号!)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions