0

我遇到了 Stoyan Stefanov 的书 Object Oriented Javascript。有一个练习如下。

练习:想象一下 Array() 不存在,并且数组文字符号也不存在。创建一个名为 MyArray() 的构造函数,其行为尽可能接近 Array()。

我已经管理了这么多,但推送不起作用。有人可以在这里指导我吗?

function MyArray() {
    var arg = arguments;
    this.toString = function () {
        var string = arg[0];
        for (var i = 1; i < arg.length; i++) {
            string += "," + arg[i];
        }
        return string;
    }
    this.length = arg.length;
    this.push = function(p) {
        var a = this.toString() + ",";
        arg[this.length] = p;
        return a.concat(p);
    }
    this.pop = function() {
        return arg[this.length - 1];
    }
    this.join = function (j) {
        var strJoin = arg[0];
        for (var i = 1; i < arg.length; i++) {
            strJoin += j + arg[i];
        }
        return strJoin;
    }
}

var a = new MyArray(1, 2, 3, "test");
console.log(a.toString()); // 1,2,3,test 
console.log(a.length); // 4
console.log(a.push('boo')); // should return 5
console.log(a.toString()); // should return 1,2,3,test,boo
console.log(a.pop()); // boo
console.log(a.join(',')); // 1,2,3,test
console.log(a.join(' isn\'t ')); // 1 isn't 2 isn't 3 isn't test

jsfiddle:http: //jsfiddle.net/creativevilla/prf3s/

4

1 回答 1

1

这是您的 push 和 pop 的固定实现:

this.push = function() {
    // edit - push needs to accept more than one new item.
    for (var i = 0; i < arguments.length; i++) {
        arg[arg.length++] = arguments[i];
    }
    return arg.length;
}
this.pop = function() {
    return arg[--arg.length];
}

小提琴:http: //jsfiddle.net/prf3s/2/

顺便说一句,我认为使用 arguments 对象(很像数组)作为内部数据存储可能有点作弊。

于 2013-09-16T10:18:13.673 回答