【JavaScript】 オブジェクトで配列のメソッドを使う
環境 CentOS 7.0 JavaScript Node.js 0.12.2
残念ながら数字キーのオブジェクトにしか適用できないが、mapやfilter,reduceとかが便利。 ポイントはオブジェクトに"length"キーを設定しておくところ。
> var o = { '1': 2, '2': 3, a: 'AAA', d: 'DDD', length: 4 }; > Array.prototype.map.call(a, function(x){return x + "add"}); [ , '2add', '3add' ] > Array.prototype.filter.call(a, function(x){return x > 0;}); [ 2, 3 ] > Array.prototype.reduce.call(a, function(x, y){return x + y;}); 5 > Array.prototype.reduceRight.call(a, function(x, y){return x + "" + y ;}); '32'