「JavaScript/制御構造」の版間の差分

削除された内容 追加された内容
M fix lint error (use script)
Ef3 (トーク | 投稿記録)
→‎for-of: for-ofとObjectの分割代入の併用
タグ: 2017年版ソースエディター
392 行
for-of 文は、Iterableオブジェクト(たとえば String Array や NodeList)に対して、反復処理を行います<ref>ES2015で追加</ref>。
 
;for-of:<syntaxhighlight lang="javascript" line>
const ary = [..."XYZ"];
 
404 行
 
Iterableでないオブジェクトが右の項に与えらてた場合、TypeError が throw されます。
;Objectはfor-of不可:<syntaxhighlight lang="javascript" highlight=3 line>
const obj = { a: 0, b: 1, c: 2};
 
412 行
</syntaxhighlight>
Object はItableではないので
;実行時エラー:<syntaxhighlight lang="text">
TypeError: obj is not iterable
となる。
</syntaxhighlight>
:となる。
 
;[https://paiza.io/projects/8oFPy97Ozwg9nv4VPeWcTw?language=javascript for-ofとObjectの分割代入の併用]:<syntaxhighlight lang="javascript" line>
const AddrBook = [
{
name: "tom",
postnumber: "420-2410",
age: 18
},
{
name: "joe",
postnumber: "420-0824",
age: 17
},
]
 
for (const { name, age } of AddrBook) {
console.log(`${name}: ${age}`)
}
 
/** 同じコンセプトのArray::forEach */
AddrBook.forEach(({ name, age }) => console.log(`${name}: ${age}`))
</syntaxhighlight>
;実行結果:<syntaxhighlight lang="text">
tom: 18
joe: 17
tom: 18
joe: 17
</syntaxhighlight>
 
== for await-of ==