for…inとfor…ofを使ってみる

ループ処理を行うfor…inとfor…ofについて、それぞれ簡単に試してみます。

for…in

for…inはオブジェクトをループする際に使用します。
主要なブラウザで特に問題なくサポートされています。

1
2
for (variable in object)
  statement

objectにオブジェクトを指定してvariableでキーを受け取り、ループ中に実行する文のstatement内でvariableを使用できます。
variableで受け取れるのはキーのみで、バリューは含まれません。

1
2
3
4
5
6
7
8
9
10
11
12
const object = {
    name: '黒川あかね',
    height: 163,
    cv: '石見舞菜香'
};
 
for(const property in object) {
  console.log(property);
}
// name
// height
// cv

for…inのデモページ

バリューを使用する場合、キーを使って取得します。

1
2
3
4
5
6
7
8
9
10
11
12
const object = {
    name: '黒川あかね',
    height: 163,
    cv: '石見舞菜香'
};
 
for(const property in object) {
  console.log(object[property]);
}
// 黒川あかね
// 163
// 石見舞菜香

for…inのデモページ2

for…of

for…inは配列やNodeListなど、反復可能オブジェクトをループする際に使用します。
IEで非対応ですが、それ以外の主要なブラウザで特に問題なくサポートされています。

1
2
for (variable of iterable)
  statement

iterableに反復可能オブジェクトを指定してvariableで値を受け取り、ループ中に実行する文のstatement内でvariableを使用できます。

1
2
3
4
5
6
7
8
const array = ['a', 'b', 'c'];
 
for (const element of array) {
  console.log(element);
}
// a
// b
// c

for…ofのデモページ

NodeListに対しても使用可能です。

1
2
3
4
5
<ul>
  <li class="item">A</li>
  <li class="item">B</li>
  <li class="item">C</li>
</ul>
1
2
3
4
5
6
7
8
const items = document.querySelectorAll('.item');
 
for (const element of items) {
  console.log(element.textContent);
}
// A
// B
// C

for…ofのデモページ2

argumentsオブジェクトなどにも使用できます。

1
2
3
4
5
6
7
8
9
10
function arr() {
  for (const value of arguments) {
    console.log(value);
  }
}
 
arr(1, 2, 3);
// 1
// 2
// 3

for…ofのデモページ3

for…of内ではbreakやcontinueを使用することもできます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const array = ['a', 'b', 'c'];
 
for (const element of array) {
  console.log(element);
  if(element === 'b') break;
}
// a
// b
 
for (const element of array) {
  if(element === 'b') continue;
  console.log(element);
}
// a
// c

for…ofのデモページ4

参考サイト

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2025年3月
 1
2345678
9101112131415
16171819202122
23242526272829
3031