Algorithm of JavaScript “sort()” Function

前端 未结 8 764
灰色年华
灰色年华 2020-12-02 17:48

Recently when I was working with JavaScript \"sort()\" function, I found in one of the tutorials that this function does not sort the numbers properly. Instead to sort numbe

8条回答
  •  [愿得一人]
    2020-12-02 18:23

    You can delegate the sorting to your own sort function:

    function sortnum(a,b) {
     return parseInt(a,10)-parseInt(b,10);
    }
    var n = ["10", "5", "40", "25", "100", "1"];
    alert(n.sort(sortnum)); //=>["1", "5", "10", "25", "40", "100"]
    

提交回复
热议问题