49
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyのイテレータメソッドと似ているJavascriptの便利なメソッド

Last updated at Posted at 2014-06-19

ECMAScript5になり、Rubyのイテレータメソッドに似たメソッドはJavascriptでも使えるようになった。それが下記のメソッドである
オブジェクトはArrayである

##forEach(Rubyのeachのようなもの)


var array = [1, 2, 3, 4, 5];
var sum = 0;

array.forEach(function(value){
  sum = value + sum  
});

console.log(sum)

//=> 15

##map(Rubyのmapのようなもの)


var array = [1, 2, 3, 4, 5];

even_array = array.map(function(value){
  return value * 2
});

console.log(even_array);

//=> [2, 4, 6, ,8, 10]

##reduce(Rubyのinjectのようなもの)


var a = [1, 3, 5, 7];

var sum = a.reduce(function(pre, value){
  return pre + value;
});

console.log(sum)

//=> 16

##filter(Rubyのselectのようなもの)

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var m = a.filter(function(value){
  return (value % 2 == 0);
});

console.log(m)

//=> [2, 4, 6, 8, 10]

##every(Rubyのall?のようなもの)


var a = [1, 2, 3, 4, 5];
var b = [1, 2, 3]

int_1 = a.every(function(value){
  return (value <= 3)
});

int_2 = b.every(function(value){
  return (value <= 3)
});

console.log(int_1); //=> false
console.log(int_2); //=> true

##some(Rubyのany?のようなもの)


var a = [1, 2, 3, 4, 5, 6, 7];

int_1 = a.some(function(value){
  return (value <= 3)
});

console.log(int_1) //=> true
49
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?