js 重写 slice

var t = [1, 2, 3];
var r = t.concat(1, 2);
console.log(r);
Array.prototype.slice = function(start, end) {
    var tem = [];
    if (arguments.length === 1) {
        start = (start + this.length) % this.length;
        for (var i = start; i < this.length; i += 1) {
            tem.push(this[i]);
        }
    }
    if (arguments.length >= 2) {
        start = (start + this.length) % this.length;
        end = (end + this.length) % this.length;
        if (end < start) {
            return [];
        }
        for (var i = start; i < end; i += 1) {
            tem.push(this[i]);
        }
    }
    return tem;
}
console.log(t.slice(-2, -1));

 

posted on 2018-11-02 16:46  偏灬爱  阅读(148)  评论(0编辑  收藏  举报

导航