Javascript 练习
2016-11-07 本文已影响43人
peerben
在Array()构造器以及相关的数组文本标识法都不存在的情况下,自定义一个类似的MyArray()构造器,并令其通过以下测试:
var a = new MyArray(1,2,3,"test");
a.toString();
//"1,2,3,test"
a.length;
//4
a[a.length-1];
//"test"
a.push("boo");
//5
a.toString();
//"1,2,3,test,boo"
a.pop();
//boo
a.toString();
//"1,2,3,test"
a.join(",");
//"1,2,3,test"
a.join(" isn\'t");
//1 isn't 2 isn't 3 isn't test"
function MyArray() {
this.length = arguments.length;
for (var i=0; i<this.length; i++){
this[i] = arguments[i];
}
this.toString = function () {
var string = "";
for (var i=0; i<this.length; i++){
string += string ? (", "+this[i]) : this[i];
}
return string;
};
this.push = function (elem) {
this[this.length] = elem;
this.length++;
};
this.pop = function () {
return this[--this.length];
};
this.join = function (sep) {
var string = "";
for(var i=0; i<this.length; i++){
string += this[i] + ((i==this.length-1) ? "": sep);
}
return string;
};
}
var a = new MyArray(1, 2, 3, "test");
console.log(a.toString());
console.log(a.length);
console.log(a[a.length-1]);
a.push("boo");
console.log(a.toString());
a.pop();
console.log(a.toString());
console.log(a.join(","));
console.log(a.join(" isn\'t "));