0
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.

JqueryのinArrayを使う際に、気を付ける。

Posted at

動機

phpのin_arrayみたいな関数がJSで使えないかなと思い、調べていると$.inArrayというのがあることを知って、使ってみたが意図しない挙動をしたのでメモ

解説

間違った書き方
const a = 10;
const b = [1,2,3,4,5];
if($.inArray(a, b)){
    alert('');
}

この処理を実行すると条件式を満たし、alertが実行される。JqueryのinArrayは、配列に含まれていたらそのインデックスを返し、含まれていなかったら-1を返す。

const a = 10;
const b = [1,2,3,4,5];
if($.inArray(a, b) !== -1){
    alert('');
}

この処理を実行すると、条件式を満たさずalertは実行されない。含まれていなかったら-1が返ってくると、覚えておく

直感的な書き方

const a = 10;
const b = [1,2,3,4,5];
if(!b.includes(a)){
    alert('');
}

arrayのprototypeにincludesという関数が用意されている。これのほうが直感的に書けて見やすいと思う。

0
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
0
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?