LoginSignup
0

More than 1 year has passed since last update.

【JavaScript】反復処理③ for...ofと反復可能性

Last updated at Posted at 2021-11-10

はじめに

Udemyの【JS】ガチで学びたい人のためのJavaScriptメカニズムの講座の振り返りです。

前回の記事

目的

  • 反復処理についての理解を深める

本題

1.for...ofと反復可能性

for...ofとはイテレーターを持つオブジェクトの反復操作を行う

イテレーターとは反復操作を行うときに使うオブジェクトのこと
→反復可能オブジェクト

ex.
String,Array,Map,Set,arguments  etc....

例1

基本的な使い方

// 配列を定義
const array = ['a', 'b', 'c'];
// for...ofを定義
// vの値に配列で格納されている値が渡ってくる
for(let v of array){
  // a b cと出力
  console.log(v);
}

例2

設定されていない値でも返す
arrayに4番目の値を取る

const array = ['a', 'b', 'c'];

// 4番目を定義する
array[4] = "e"

for(let v of array){
  // cの後にundefined e と出力される
  // 3番目の値が定義されていないため
  console.log(v);
}
const array = ['a', 'b', 'c'];

array[4] = "e"

// プロトタイプの値でも返却することはない
// methodメソッドがループで出現しない
Object.prototype.method = function(){}

// 配列のイテレーターではenumerableを参照していない
Object.defineProperty(array, 0, {
  // 配列の0番目(a)がループで返ってくる
  enumerable: false
})

const d = Object.getOwnPropertyDescriptor(array, 0);
// この結果もenumerableはfalseとなっている
console.log(d);

for(let v of array){
  console.log(v);
}

今日はここまで!

参考にさせて頂いた記事

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