Objectオブジェクトのイテレーター
読了まで:約1分
概要: Object オブジェクトの
Javascript にはObject.prototype
をObject.prototype
にObject.prototype.forEach
がobject **_forEach*_**
じゃ
実際の
Object.Iterator = function ( target ) {
if ( typeof(target) != 'object' )
throw new TyprError('Arguments is not object.');
var self = this;
self.target = function () {
return target;
}
}
Object.Iterator.prototype = {
'filter' : function ( callback, thisObject ) {
if ( typeof(callback) != 'function' )
throw new TypeError('callback is not function');
var obj = this.target(),
result = {};
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
if ( callback.call(thisObject, key, obj [[key]] , obj) ) {
result [[key]] = obj [[key]] ;
}
}
}
return result;
},
'each' : function ( callback, thisObject ) {
if ( typeof(callback) != 'function' )
throw new TypeError('callback is not function');
var obj = this.target();
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
callback.call(thisObject, key, obj [[key]] , obj);
}
}
},
'map' : function ( callback, thisObject ) {
if ( typeof(callback) != 'function' )
throw new TypeError('callback is not function');
var obj = this.target(),
result = {};
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
result [[key]] = callback.call(thisObject, key, obj [[key]] , obj);
}
}
return result;
},
'every' : function ( callback, thisObject ) {
if ( typeof(callback) != 'function' )
throw new TypeError('callback is not function');
var obj = this.target();
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) && ! callback.call( thisObject, key, obj [[key]] , obj ) ) {
return false;
}
}
return true;
},
'some' : function ( callback, thisObject ) {
if ( typeof(callback) != 'function' )
throw new TypeError('callback is not function');
var obj = this.target();
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) && callback.call( thisObject, key, obj [[key]] , obj ) ) {
return true;
}
}
return false;
},
'keys' : function () {
var obj = this.target(),
results = [];
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) )
results [[results.length]] = key;
}
return results;
},
'values' : function () {
var obj = this.target(),
results = [];
for ( var key in obj ) {
if ( obj.hasOwnProperty(key) )
results [[results.length]] = obj [[key]] ;
}
return results;
}
};
で、
var hash = { 'aaa': 'AAA', 'bbb': 'BBB', 'ccc': 'CCC' };
var iterator = new Object.Iterator( hash );
iterator.keys() // [[ 'aaa', 'bbb', 'ccc' ]]
こうすれば、
ちなみに
とり
#FIXME