Javascript native sort method code

后端 未结 3 1672
时光说笑
时光说笑 2020-12-04 01:58

Any idea how I can view the implementation of native javascript methods specifically the sort method. The reason why I am looking for this I am just wondering what the alg

3条回答
  •  一向
    一向 (楼主)
    2020-12-04 02:40

    Unfortunately, there doesn't appear to be a standardized method.

    Until that time comes, you could write your own simple alphabetization function:

    sortObject = function (){
        var arr = [], i;
        for(i in this){
            arr.push({index:i,content:this[i]});
            delete this[i];
        }
        arr.sort();
        for(i in arr){
            var item = arr[i];
            this[item.index] = item.content;
        }
        return this; // make chainable
    }
    var obj = {
        acronym: "OOP",
        definition: "Object-Oriented Programming",
        article: "http://wikipedia.org/OOP"
    };
    sortObject.apply(obj); // indices are "acronym", "article", "definition"
    

    I know this question was asked over a year ago, but I hope this helps you as well as anyone with the same problem.

提交回复
热议问题