constructor that behaves as close to Array()
by Anchit Gupta
HTML
<h1>6. 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.</h1>
JavaScript
var myArray = function () {
this.arrVal = arguments;
};
myArray.prototype.length = function() {
var lenArr=0;
for(var len in this.arrVal){
lenArr+=1;
}
return lenArr;
};
myArray.prototype.toString=function(){
var lenArr = this.length(),commaSep='';
var lastIndex = lenArr-1;
for(var i=0;i<lenArr;i++){
if(i==lastIndex)
commaSep+=this.arrVal[i];
else
commaSep+=this.arrVal[i]+",";
}
console.log(commaSep);
};
myArray.prototype.join=function(joinChar){
var lenArr = this.length(),joinStr='';
var lastIndex = lenArr-1;
for(var i=0;i<lenArr;i++){
if(i==lastIndex)
joinStr+=this.arrVal[i]+joinChar;
else
joinStr+=this.arrVal[i]+joinChar+" ";
}
console.log(joinStr);
};
myArray.prototype.push=function(valToPush){
var lastIndex = parseInt(this.length());
this.arrVal[lastIndex]=valToPush;
//this.arrVal.concat(valToPush);
console.log(this.arrVal);
return this.arrVal;
};
var arr1 = new myArray(1,2,3,4,5,6,122,255,'a','b','nn');
// call the Length method.
arr1.push("Mango");
alert("Length of given array is : "+arr1.length());
arr1.toString();
arr1.join("%");