callback 回调函数

把函数a当做一个参数传入函数b

<script>
Array.prototype.mysort = function(callback){
    let s = this;
    
    //准备向回调函数里传值的参数
    let a,b;
    for(i=0;i<s.length;i++){
        a = i;
        b = s[i];
        //此键的值就取决于回调函数的返回值
        s[i] = callback(a,b);
    }
    
    
    return s;
}

function sortNumber(x,y){
    return parseInt(x)+parseInt(y);
}

var arr = new Array(6)
arr[0] = "3"
arr[1] = "1"
arr[2] = "4"
arr[3] = "6"
arr[4] = "2"
arr[5] = "3"

console.log(arr.mysort(sortNumber));
</script>

 

posted @ 2018-11-09 09:19  fleam  阅读(196)  评论(0编辑  收藏  举报