我遇到了Stoyan Stefanov的“面向对象的Javascript”一书。有一项练习如下。
练习:想象数组()不存在且数组文字符号不存在 无论是。创建一个名为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
答案 0 :(得分:1)
这是你推送和弹出的固定实现:
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对象(非常像数组)作为内部数据存储可能有点作弊。