js对数组中的数字排序

1 前言

如果数组里面都是数字,如果用原生的sort,默认是按字符串排序的,不符合我们的要求

2 代码

方法1:添加Array的原生方法

Array.prototype.sort2 =function(){
    //实现数字升序
    this.sort(function (a,b){ return a-b });
};

方法2:不写原生方法

  var arr=[1,4,8,2,11,7,3,5];
  arr.sort(function (a,b){ return a-b });//arr = [1,2,3,4,5,7,8,11]

猜你喜欢

转载自www.cnblogs.com/fanbi/p/9013432.html