1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| // constructor par défaut prenant des éléments ou la longueur
// exemple d'utilisation :
// var myArr = new myArray(1,2,3); -> [1,2,3]
// var myArr = new myArray(4); -> [,,,]
function myArray(len){
if(arguments.length==1 && typeof(len)=='number')
this.push.apply(this,(new Array(len)));
else
this.push.apply(this,arguments);
}
// ajout des méthodes de array en écrassant le prototype (~héritage)
myArray.prototype = new Array();
// [INUTILE] correction de l'attribut "constructor" (qui a été écrasé à la ligne au dessus)
myArray.prototype.constructor = myArray;
// création d'une méthode "toArray"
myArray.prototype.toArray = function(){
return this.slice();
};
// correction de la méthode "toString" (qui plantait sous certains navigateurs comme chrome)
myArray.prototype.toString = function(){
return this.toArray().toString();
};
// ajout d'un "init" qui ajoute les éléments d'un array à l'objet courant
// exemple d'utilisation :
// var myArr = (new myArray()).init([1,2,3]);
myArray.prototype.init = function(array){
this.push.apply(this,array);
return this;
};
// correction de la méthode "concat" (qui renvoyait un array au lieu d'un myArray)
myArray.prototype.concat = function(){
var a = this.map.call(arguments,function(e){return e.toArray?e.toArray():e;});
return (new myArray()).init([].concat.apply(this.toArray(),a.toArray()));
};
//------------------------------------
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
//if(!myArray.prototype.map){
myArray.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
A = new myArray(len);
k = 0;
while(k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[ k ];
mappedValue = callback.call(T, kValue, k, O);
A[ k ] = mappedValue;
}
k++;
}
return A;
};
//}
//------------------------------------
function dump(e){
document.write(e,'<br/>');
}
var a = new myArray(1,2,3);
var b = a.concat([4,5,6],[7,8,9,0],a);
for(var i in b)
dump(i+" : "+b[i]);
dump('---');
for(var i in a)
dump(i+" : "+a[i]); |
Partager