LoginSignup
9
6

More than 5 years have passed since last update.

Array.prototype.includesとArray.prototype.indexOfの違い

Last updated at Posted at 2018-11-03

はじめに

配列がある要素を含むか判定することはよくありますよね。その時に使われるメソッドとしては表題の二つがあります。
ちなみに私は基本的にincludesを使います。だってindexOfは結果と-1を比較しないとBooleanが取り出せないし、文字数多いもん。
恥ずかしながらarr.includes('a')arr.indexOf('a') !== -1は微妙に異なることに最近気が付いたので、調べたついでにまとめました。
このメソッドを使う時はBooleanを取り出したいことが多いので、その例を使います。

まず使い方

const arr = [1, 2, 3]
// indexOfは存在しない場合-1を返す
arr.indexOf(1) !== -1 // true
arr.includes(1) // true

どちらも第二引数にfromIndexを指定することもできます

null

const arr = [null]

arr.indexOf(null) !== -1 // true
arr.includes(null) // true

undefined

const arr = [undefined]

arr.indexOf(undefined) !== -1 // true
arr.includes(undefined) // true

これは同じ結果ですが、

const arr = [,]

arr.indexOf(undefined) !== -1 // false !!!
arr.includes(undefined) // true

これはindexOfではundefinedとは異なる扱いを受けるようです。

a=[,]とした時にa[0]undefinedなのでincludesの挙動が正しい気がします。
※2018/11/5追記
indexOfはあくまでindexを返す為に存在するので、indexが存在しない[,]では-1を返すという挙動をするようになっているようでした。
もちろん

const arr = []

arr.indexOf(undefined) !== -1 // false
arr.includes(undefined) // false

です

NaN

const arr = [NaN]

arr.indexOf(NaN) !== -1 // false !!!
arr.includes(NaN) // true

NaNはindexOfでは見つけられません。

まとめ

  • Array.prototype.includesArray.prototype.indexOfの挙動はだいたい同じ
  • indexOfNaN空の要素を見つけられない
9
6
2

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
9
6