for文
文・・・なのか?
JavaScript
for
code:js
for (let i = 0; i < 9; i++) {
console.log(i)
}
クロージャを使う時、スコープに注意する
for await...of
ジェネレータ(Unityのコルーチンみたいなやつ)に関する機能
yieldで区切ったメソッドをforEachする。使わん
for...in
code:js
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(${property}: ${object[property]});
}
プロパティを反復する
配列に使うと想定しないプロパティを拾うので注意
arrayで言うと、lenghtプロパティも引っかかる
そもそもプロトタイプチェーン配下も拾うので、使い勝手が悪い
C#のfor...inとゴチャる
for...of
code:js
const array1 = 'a', 'b', 'c';
for (const element of array1) {
console.log(element);
}
配列向けの反復
配列以外にも色々使えるものがある(文字列とか)
Object.entries()
code:js
const foo = { a: 1, b: 2, c: 3 };
for (const key, value of Object.entries(foo)) {
console.log(key, value);
}
Objectを反復する場合
foreach文
イテレータに対して繰り返し処理をする
C#
code:cs
string[] strings = new string3{"A", "B", "C"};
foreach(string item in strings)
{
print (item);
}
インデックス番号が取れないのが玉にキズ
ruby
code:ruby
strings = "First", "Second", "Third"
string.each do |str|
p str
end
php
code:php
$strings = "A", "B", "C";
foreach($strings as $string) {
var_dump($string);
}
foreach($strings as $index => $string) {
var_dump($index);
var_dump($string);
}
ForEachメソッド
コレクションAPIが発達してる言語とかだと、コレクション側に各要素に対して処理をするラムダ式を渡せるメソッドがあったりする。