LoginSignup
6
3

More than 5 years have passed since last update.

javascriptの「配列ライク」の罠

Last updated at Posted at 2017-11-02

javascriptのドキュメントで登場する「配列ライク」

例えば、「getElementsByClassName」メソッド。
https://developer.mozilla.org/ja/docs/Web/API/Document/getElementsByClassName

与えられたクラス名で得られる要素の配列ライクのオブジェクトを返します。document オブジェクトで呼び出されたときは、ルートノードを含む、完全な文書が検索されます。任意の要素でgetElementsByClassName() を呼び出すこともできます。その場合は、与えられたクラス名を持つ指定されたルート要素下の要素だけが返ります。

なるほど、つまり、配列形式で帰ってくるんだな。確認してみる。

sample.js
 tests = document.getElementsByClassName('test')
 console.log(tests) // [<div class='test'>1</div>,<div class='test'>2</div>,...]

確かに、配列で帰ってる。(ように見える…)

だけど、

sample.js
 tests = document.getElementsByClassName('test')
 tests.forEach(...) // TypeError

とエラーになる。

配列ライクは配列ではない

言われれば当たり前だが、配列ライクは配列ではないのだ。したがって、配列(Array)に対して用意されているメソッド
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array
はそのままでは使えない。

対処法

今回はforEachがやりたかったので以下の記事が参考になった。Array.prototype.forEach.call()を使うのが基本的な対処法らしい。

http://ptech.g.hatena.ne.jp/noromanba/20120521/1337639496
http://ism1000ch.hatenablog.com/entry/2014/07/30/024635

6
3
4

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