Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

Array​.prototype​.slice.call について

Last updated at Posted at 2019-05-24

こう言う悪魔的記法に出会った。

const nodeListOfDiv = document.querySelectorAll("div")
const length = nodeListOfDiv.length
const arrayOfDiv = Array.prototype.slice.call(nodeListOfDiv, 0, length)

意味

上記のコードは [object NodeList][object Array] に変換している。

文法

const arrayOfDiv = Array.prototype.slice.call(
  nodeListOfDiv, // 第一引数はインスタンス this, Python で言えば self
  0, length      // 第二引数以降はメソッドの引数, slice の引数になる
)                                           

Function.prototype.call と言うことは関数オブジェクトのメソッドと言うことか...

Function​.prototype​.call() - MDN Web docs
call() はあるオブジェクトに所属する関数やメソッドを、別なオブジェクトに割り当てて呼び出すことができます。

slice(begin, end) は引数を省略すると、 0, length が代入される様子。

Array​.prototype​.slice() - MDN Web docs
begin が指定されなかった場合、 slice はインデックス 0 から開始します。
end が省略された場合、slice はシーケンスの最後 (arr.length) までを取り出します。

用途

for ... in, for ... of, forEach で使えるようにするため。そのままでは使えないから... って書いてあったけど普通に Chrome で使えた。最近使えるようになったのかな...

const nodeListOfDiv = document.querySelectorAll("div")
for (nodeOfDiv in nodeListOfDiv) {
  console.log(nodeOfDiv);
}
const nodeListOfDiv = document.querySelectorAll("div")
const length = nodeListOfDiv.length
for (let i = 0; i < length; i++) {
  console.log("hello");
  console.log(nodeListOfDiv[i]);
}
const nodeListOfDiv = document.querySelectorAll("div")
nodeListOfDiv.forEach(function(e, i) { console.log(i + ': ' + e); });

型判定

typeof では正確に判定できないらしい。

参考にさせていただいたもの

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?