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

indexOfとincludesで存在チェックの結果が変わる理由:NaNと配列の穴をNode.jsで実測

2
Posted at

indexOf(NaN) は -1 でも includes(NaN) は true。「含まれるか」を調べるコードでも、比較の規則は同じとは限りません。

AIが書いた存在チェックは、戻り値と比較方法を分けて確認します。以前の速度比較とは別に、今回は判定結果の違いを調べます。

実行環境

2026年11月12日、macOS 27.2 / Node.js v24.22.1 で、以下のコードを掲載順に1つの .mjs ファイルとして実行しました。

node example.mjs

ブラウザ・Windows・速度は未検証です。

NaN は includes なら見つかる

const values = [NaN, 0, "0"];
console.log("NaN:", values.indexOf(NaN), values.includes(NaN));
console.log("number:", [0].indexOf("0"), [0].includes("0"));
NaN: -1 true
number: -1 false

indexOf は見つけた位置を返し、見つからないと -1。厳密等価と同じ比較規則なので、NaN 同士も一致しません。

includes は真偽値を返し、SameValueZero という規則で NaN 同士も一致と扱います。ただし、数値の 0 と文字列の "0" は別物。

計算結果に NaN が混じるなら、単純な置き換えでも期待値の確認が必要です。

穴と undefined でも差が出る

const sparse = Array(1);
console.log("hole:", sparse.indexOf(undefined), sparse.includes(undefined));
console.log("own:", Object.hasOwn(sparse, 0));
console.log("explicit:", [undefined].indexOf(undefined), [undefined].includes(undefined));
hole: -1 true
own: false
explicit: 0 true

Array(1) は長さ1でも、添字0の要素を持ちません。この未作成の位置が「穴」です。

indexOf は存在しない位置を飛ばします。includes は値を読み、この例の穴を undefined として扱います。実際に undefined を入れた配列なら、どちらでも見つかります。

includes(undefined) だけで「undefined を代入した」とは判断できません。位置の有無は Object.hasOwn(array, index) などで別に確認します。この実測ではプロトタイプに数値プロパティを追加していません。

indexOf の戻り値を、そのまま if に渡さない

const names = ["alice", "bob"];
console.log("bad:", Boolean(names.indexOf("alice")), Boolean(names.indexOf("zoe")));
console.log("good:", names.indexOf("alice") !== -1, names.includes("alice"));
bad: false true
good: true true

先頭で見つかると 0 なので真偽値では false。見つからない -1 は true です。if (names.indexOf(name)) は意図と逆の判定になりえます。

位置が必要なら結果を -1 と比較し、存在だけ知りたいなら includes を選べます。ただし NaN や穴の違いも考慮します。

参照


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

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