StackOverflow 18825078 Asked
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. Test with this code:
JavaScript
function MyArray() {
var arg = arguments;
this.toString = function (x) {
var string = arg[0];
for (var i = 1; i < arg.length; i++) {
string += "," + arg[i];
}
if (x !== undefined) {
string + "," + x;
}
return string;
}
this.length = arg.length;
this.push = function (p) {
arg[arg.length++] = p;
return arg.length;
}
this.pop = function () {
return arg[--arg.length];
}
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