Question from Object-Oriented JavaScript book: 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 thought it would be a good challenge to test my skills. This is what I came up with, but it doesn’t work and is very incomplete.. I am a bit stumped:
function MyArray(){
// PRIVATE FIELDS -----------------------
var initialData = arguments;
var storage;
// PRIVATE METHODS ----------------------
function refresh(){ //this doesn't work :(
for(var i = 0; i < storage.length; i++){
this[i] = storage[i]
}
};
function initialize(){
storage = initialData;
refresh();
}
function count(){
var result = 0;
for(var item in this){
//console.log(item, parseInt(item), typeof item);
if(typeof item == 'number'){
result++;
}
}
return result;
};
initialize();
// PUBLIC FIELDS -------------------------
this.length = count();
// PUBLIC METHODS ------------------------
//todo:
this.push = function(item){
refresh();
}
this.pop = function(){}
this.join = function(){}
this.toString = function(){}
}
var c = new MyArray(32,132,11);
console.log(c, c.length);
This isn’t for any production code or any project.. just to try to learn JavaScript a lot more. Can anyone try to help me with this code?
The thing is that you can use arguments object. It’s not an array that was created with Array() so you won’t break rules of the exercise. Here’s what you need to do:
I forgot to mention that ANY object is an associative array, so it’s not a wrong thing to apply associative arrays for the exercise as we don’t use the Array() object itself.
To author of the question: in your example you use: this[“i”] = storage[i] that equals to this.i = storage[i]. Try to remove quotes and use it like this[i] = storage[i]