如何在数组原型链上补充一个选择排序方法?顺便手写一个选择排序

56 阅读1分钟

思路:因为包装对象的原型中this指向实例,这使我们可以让实例调用自定义的方法,对自身进行排序

        function newSort() {
            this.forEach((item, index) => {
                for(let i = index; i < this.length; i++) {
                    if(this[index] >= this[i]) this.splice(index, 0, this.splice(i, 1)[0])
                }
            })
        }
        Array.prototype.newSort = newSort
        const arr = [7, 5, 5, 3, 6]
        arr.newSort()
        console.log(arr);