I came across book Object Oriented Javascript by Stoyan Stefanov. There is one exercise as below.
Exercise: Imagine Array() doesn't exist and the array literal notation doesn't exist either. Create a constructor called MyArray() that behaves as close to Array() as possible.
I have managed this much but push is not working. Can anybody guide me here?
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/
thisinpush???popis actuallypeek... In short, you keep neglecting to keep thelengthproperty updated.