js sort numbers in an array

1 Introduction

If the array is full of numbers, if the native sort is used, the default is to sort by strings, which does not meet our requirements

2 code

Method 1: Add the native method of Array

Array.prototype.sort2 =function(){
    //implement numbers in ascending order
    this.sort(function (a,b){ return a-b });
};

Method 2: Do not write native methods

  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]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326043678&siteId=291194637