LoginSignup
0
0

More than 3 years have passed since last update.

【javascript】イテラブル 文字列

Last updated at Posted at 2020-07-15

この記事は以下の書籍を参考にして執筆しました。

[..."Isasaka"]//["I", "s", "a", "s", "a", "k", "a"]

文字列を反復すると一連の文字が生成される

なぜ文字なのか

それを決めるのは文字列のイテレータ
文字の代わりにカスタムイテレータで文字列のイテレータを書き換えてみる。

const myString = Object("Iterables are quite something")

myString[Symbol.iterator] = function*() {
  for (const word of this.split(' ')) yield word
}

const words = [...myString]// ["Iterables", "are", "quite", "something"]

出典:入門JavaScriptプログラミング

ここでは文字列を作成し、文字列オブジェクトを作成するためにObject呼び出しで囲んでいる
こうしないとプロパティを更新しても維持できない。

次は文字の代わりに単語を生成するカスタムイテレータを文字列の@@iteratorに割り当てる。

オブジェクトの@@iteratorを上書きするときは注意
オブジェクト自体のイテレータを使って反復処理をした場合、無限ループになる。

const myArray = Object([2, 3, 5])

myArray[Symbol.iterator] = function*() {
  const copy = [...this] //カスタムイテレータの中で
                        //thisを反復しようとしている。
  copy.reverse();
  for (const item of copy) yield item
}

const a = [...myArray]

出典:入門JavaScriptプログラミング

イテレータの中で[...this]をしていると、
値を取得するためにthisの反復処理をしようとする
→イテレータを使用する必要がある
→すでに入れテータの中にいるので再帰呼び出し

0
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
0
0