4
0

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.

javascriptのLambdaの失敗あるある

Last updated at Posted at 2018-04-25

javascriptで何らかの配列に対する処理を書いて、

filttered = [];
[1,2,3,4].forEach((i) => {
  //1,3以外を取得
  if ([1,3].indexOf(i) < 0) {
    filttered.push(i);
  }
});
console.log(filttered); //[2,4]

で、これはfilterで行けると思い修正

filttered =
  [1,2,3,4].filter((i) => {
   //1,3以外を取得
   return [1,3].indexOf(i) < 0;
  });
console.log(filttered); //[2,4]

さらに、1行で済むよねと思い修正

//1,3以外を取得
filttered =
  [1,2,3,4].filter((i) => {[1,3].indexOf(i) < 0 });
console.log(filttered); //[] ????

突然値が返らなくなり焦ることがあります。

理由は単純でブロック {} を残してるのに return が無いから
lambdaでreturnを省略する時は{}を外すのを忘れずに!

//1,3以外を取得
filttered =
  [1,2,3,4].filter((i) => [1,3].indexOf(i) < 0);
console.log(filttered); //[2,4]
4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?