定義と使い方
配列におけるincludes()関数は、指定された配列に特定の要素が含まれているかどうかを確認し、含まれていればtrue、含まれていなければfalseを返します。
この関数を使用すると、配列に特定の要素が含まれているかをチェックする際に非常に便利です。
検索する要素が文字列の場合、大文字と小文字を区別します。
基本例
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // 出力: true
console.log(arr.includes(6)); // 出力: false
文字列では、文字列 includes()が文字列に特定の文字列が含まれているかどうかを確認する関数です。
構文
arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
arrは、includes()関数を適用する配列です。
引数
searchElement |
配列内で検索する要素です。 |
|---|---|
fromIndex |
オプション。検索を開始する0から始まるインデックスです。(配列のインデックスは0から始まります。)省略した場合は、デフォルト値として 0が使用されます。もし負の値を指定した場合は、配列の末尾から逆方向に検索を開始します。 |
戻り値
配列に指定された要素が含まれている場合はtrueを、含まれていない場合はfalseを返します。
引数と戻り値の例
データ型の区別
配列のincludes()関数は、検索する要素のデータ型を明確に区別します。
const numbers = [10, 20, 30, 40, NaN];
console.log(numbers.includes(30)); // true
console.log(numbers.includes("30")); // false
console.log(numbers.includes(15)); // false
console.log(numbers.includes(40, 3)); // true
console.log(numbers.includes(20, -2)); // false
console.log(numbers.includes(NaN, -2)); // true
const words = ["apple", "banana", "orange", "grape", "1"];
console.log(words.includes("banana")); // true
console.log(words.includes("pear")); // false
console.log(words.includes("grape", 2)); // true
console.log(words.includes("apple", -4)); // false
console.log(words.includes("banana", -4)); // true
console.log(words.includes(1)); // false
文字列の大文字と小文字の区別
配列のincludes()関数は、検索する要素が文字列の場合、大文字と小文字を区別します。
const words = ["apple", "banana", "orange"];
console.log(words.includes("apple")); // true
console.log(words.includes("Apple")); // false
文字列の一致
配列のincludes()関数は、検索する要素が文字列の場合、指定された文字列と完全に一致した場合にのみtrueを返します。一致せず、文字列の一部だけが一致する場合はfalseを返します。
const words = ["apple", "banana", "orange"];
console.log(words.includes("banana")); // true
console.log(words.includes("ban")); // false
変数の存在確認
const car = "My car";
const words = ["apple", "banana", car];
console.log(words.includes(car)); // true
console.log(words.includes("My car")); // true
注意点
配列でincludes()関数を使用する際には、いくつか注意すべき点があります。
NaNの比較と包含
JavaScriptでは、NaNは自分自身と等しくありません。つまり、NaN === NaNは常にfalseになります。
しかし、配列ではincludes()関数を使用して、配列にNaNが含まれているかどうかを確認することができます。
console.log(NaN === NaN); // false
const values = [1, NaN, 3, 4, 5];
console.log(values.includes(NaN)); // true
疎配列でincludes()を使用する
疎配列でundefinedを検索すると、trueを返します。
const arr = [1, , 3];
console.log(arr.includes(undefined)); // true
互換性
| メソッド |
デスクトップ Chrome
|
デスクトップ Edge
|
デスクトップ Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
includes()
|
47 | 14 | 43 | 9 | 6 |
仕様書
| 仕様書 | |
|---|---|
includes()
|
ECMAScript® 2026 Language Specification #sec-array.prototype.includes |