ホームページ  >  記事  >  ウェブフロントエンド  >  js のいくつかの異なるループの紹介 (コード付き)

js のいくつかの異なるループの紹介 (コード付き)

不言
不言オリジナル
2018-08-27 11:34:361535ブラウズ

この記事では、js のさまざまなループを紹介します (コード付き)。必要な方は参考にしていただければ幸いです。

JavaScript には、ループを反復するためのメソッドが多数用意されています。

for

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  console.log(list[i]) //value
  console.log(i) //index
}
  • Break を使用して for ループを中断できます

  • for ループの次の反復を続行するには continue を使用できます

forEach

ES5 で導入されました。配列を指定すると、list.forEach() を使用してそのプロパティを反復処理できます。

const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
list.forEach((item, index) => {
  console.log(item) //value
  console.log(index) //index
})

//index is optional
list.forEach(item => console.log(item))
ただし、このループから抜け出すことはできないことに注意してください。

do...while

const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
let i = 0
do {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
} while (i < list.length)

Break を使用して while ループを中断できます:

do {
  if (something) break
} while (true)

continue を使用して次の反復にジャンプできます:

do {
  if (something) continue

  //do something else
} while (true)

while

const list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
let i = 0
while (i < list.length) {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
}

Break を使用して while ループを中断できます:

while (true) {
  if (something) break
}

次の反復にジャンプするには continue を使用できます:

while (true) {
  if (something) continue

  //do something else
}

do...while との違いは、 do...while は常にループを少なくとも 1 回実行することです。

for...in

プロパティ名を指定して、オブジェクトの列挙可能なすべてのプロパティを反復処理します。

for (let property in object) {
  console.log(property) //property name
  console.log(object[property]) //property value
}

for...of

ES2015 では、forEach のシンプルさとハッキング能力を組み合わせた for ループが導入されました。

//iterate over the value
for (const value of [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]) {
  console.log(value) //value
}

//get the index as well, using `entries()`
for (const [index, value] of [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;].entries()) {
  console.log(index) //index
  console.log(value) //value
}

const の使用に注意してください。このループは反復ごとに新しい範囲を作成するため、let の代わりに安全に使用できます。

for...in VS FOR...OF

とfor...inの違いは次のとおりです:

  • for...of iteration属性値

  • for...in iteration属性名

関連する推奨事項:

JS の for while ループ

js の for in ループと Java の foreach ループの違いの分析

以上がjs のいくつかの異なるループの紹介 (コード付き)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。