ホームページ  >  記事  >  ウェブフロントエンド  >  初心者のための JavaScript ループ: 基本を学ぶ

初心者のための JavaScript ループ: 基本を学ぶ

PHPz
PHPzオリジナル
2024-07-18 18:25:221030ブラウズ

JavaScript Loops for Beginners: Learn the Basics


憂鬱な月曜日、あなたは仕事中です。月曜日が憂鬱になることは誰でも知っていますよね?あなたの上司があなたに近づき、「週末に受け取った未開封のメールが 300 通あります。各メールを開いて送信者の名前を書き留め、読み終わったらメールを削除してください。」

このタスクを手動で実行しようとすると、非常に面倒に見えます。次に考えているのは、Google にアクセスして、このプロセスを自動化し、作業を楽にしてくれるソフトウェアを探すことでしょう?

そうですね、プログラミングでも似たような状況があります。完了するまで繰り返しタスクを実行する必要がある場合があります。この問題をどうやって解決しますか? JavaScript にはループと呼ばれるものがあります。ループを使用すると、タスクを完了するために必要なコードの量を減らすことで、繰り返しのタスクを解決できます。

この記事では、ループとは何か、その仕組み、そしてそれをプログラムに適用するために使用できるさまざまな方法について説明します。

ループとは何ですか?

ループは、繰り返しのアクションを簡単に実行するために JavaScript で使用されます。これらは、true または false を返す条件に基づいています。

条件は、ループの実行を維持するために渡す必要がある式です。ループは、指定された条件が true 値を返すと実行され、false 値を返すと停止します。

ループを使用する必要があるのはどのような場合ですか?

ループは、反復的なタスクを実行するのに役立ちます。たとえば、ループを使用すると、問題を解決するために必要なコードが短縮されます。時間を節約し、メモリ使用量を最適化し、柔軟性を向上させます。

ループの真の意味は、コード長の短縮や繰り返しの制限を超えています。これらは、配列、オブジェクト、またはその他の構造内のデータを操作するときにも役立ちます。さらに、ループはコードの繰り返しを減らし、コードの再利用性を高めることでコードのモジュール性を促進します。これにより、プロジェクトのさまざまな部分で使用できるコードを作成できるようになります。

ループの種類

ループには、開始制御ループと終了制御ループの 2 つの主要なカテゴリがあります。

エントリ制御 ループは、ループ本体を実行する前に「ループの入り口」で条件を評価します。条件が true の場合、ボディは実行されます。そうしないと体が動きません。 for ループと while ループは、エントリ制御ループの例です。

終了制御 ループは、テスト条件よりもループの本体に焦点を当て、テスト条件を評価する前にループの本体が少なくとも 1 回実行されるようにします。 Exit 制御ループの良い例は do-while ループです。

エントリ制御ループの例をいくつか見てみましょう:

while ループ

while ループの構文は次のとおりです。

while (condition) {
  //  loop's body
}

次のリストでは、while ループの機能について説明します。

  1. while ループは括弧内のテスト条件を受け取ります。
  2. プログラムは条件をチェックして、合格か不合格かを確認します。
  3. ループ本体内のコードは、条件が渡される限り実行されます。
  4. テスト条件が不合格になると、プログラムは動作を終了します。

以下では、while ループの実際的な例を見てみましょう:

let arr = [];
let i = 1;
let number = 5;

while (i <= number) {
arr.push(i)
i++
}
console.log(arr)
  1. 上記のコード スニペットは、「arr」、「i」、および「num」変数を初期化します。
  2. 「arr」変数は、テスト条件を通過する値を保持する配列です。
  3. 「i」変数は、各反復後の各増分を追跡します。
  4. 「number」変数は、各反復後に「i」の値をその値 (5) と比較します。
  5. ループ本体内のコードは、「i」が「number」以下である限り、各反復後に「i」の各値を配列にプッシュします。
  6. 「i」の現在の値が条件を満たさないと、この場合は「i」の値が「number」である 6 より大きいため、ループの実行が停止します。

push() メソッドは、配列の末尾に新しい項目を追加する組み込みの JavaScript 関数です。

出力

[1, 2, 3, 4, 5]

do-while ループ

do-whileloop は while ループによく似ています。 while と do-while ループの主な違いは、do-while ループではループの条件を評価する前に少なくとも 1 回はコードが実行されることを保証することです。do-while ループの構文は次のとおりです。

do {
  // loop's body
}
while (//condition)

do-while は、終了制御ループの優れた例です。これは、終了制御ループがテスト条件よりもループ本体を優先するという事実にあります。次に、do-while ループを利用した実際的なコード例を詳しく見てみましょう。

例:

let i = 1;
let num = 5;

do {
  console.log(i);
  i++;
} while (i <= num);

次に、このコード スニペットを分析してみましょう:

  1. We initialized the "i" and "num" variables.
  2. The console logs in the value of "i" (1) before evaluating the loop's condition.
  3. The condition is checked, and the value of "i" increments with +1 after each iteration.
  4. The loop ends its operation once "i" is greater than "num".

Output

1
2
3
4
5

Although the do-while loop is very much similar to the while loop, there are subtle differences we must note, let’s take another example that compares the difference between the while and do-while loop.

let i = 5;
let num = 4

while( i < num)
{
  console.log(i)
}

This while loop above won't return any result to the console, now why is this so?

  1. We initialized the "i" and "num" variables with values of 5 and 4, respectively.
  2. The condition checks if the value of "i" is less than "num".
  3. If true, it logs in each respective value.
  4. Since the initial value of "i" exceeds that of "num", the loop never runs.

now let's take a similar example with the do-while loop.

let i = 5;
let num = 4;

do {
  console.log(i)
}
while ( i < num)

Output

5

The do-while loop ensures the execution of the code block, which returns 5 into the console, although "i" has a higher value than "num" initially, it's still logged in the console once. This representation shows you the difference in functionality between the do-while and while loop.

For loop

The for loop is a unique type of loop and one of the most commonly used loop by programmers, the for loop is a loop that runs a code block for a specific number of time depending on a condition. The for loop has the following syntax below.

for (Expression1...; Expression2....; Expression3...{
     //code block
}

Expression1: This part of a for loop is also known as the initialization area, it's the beginning of our for loop and the area where the counter variable is defined; the counter variable is used to track the number of times the loop runs and store that as a value.

Expression2: This is the second part of the loop, this part defines the conditional statement that would execute the loop.

Expression3: This is where the loop ends; the counter variable in this section updates its value after each iteration either by increasing or decreasing the value as specified in the condition.

Let's dive into an example using the for loop.

for (let i = 0; i < 100; i++) {
    console.log("Hello World" )
}

From the code snippet above, let's break it down together.

  1. First, we've initialized the counter variable "i" with a value of zero.
  2. Next, we've created the conditional statement that would keep the code running.
  3. We compared the value of "i" with 100, if it passes this test, "Hello World" is logged.
  4. This process repeats while the counter increases with +1 after each iteration.
  5. The loop ends once the counter's value reaches 100.

Output

Hello World
Hello World
Hello World

...

//repeated 97 more times making it 100 "Hello World" in total
...

for-each loop

The for-each loop is a method in JavaScript that travels through an array and applies a callback function on each element in that array; a callback function is simply another function passed as a parameter into a function, the callback function works by running sequentially after the main function is done executing.

Let's examine the basic syntax of a for-each loop.

array.forEach(function(currentValue, index, arr))

The provided code above explains the workings of a for-each loop.

  • This loop accepts three parameters, which are the current value, an index, and an array.
  • The current value represents the present value of the element in the array.
  • The index is an optional parameter that tells you the numbered position of the current element in that array.
  • The arr is another optional parameter that tells you what array the element belongs to.
let myArray = [1, 2, 3, 4, 5];

array.forEach((num, index, arr) => {
  arr[index] = num * 2;

  console.log(array);
});

Let's break down the example above:

  1. We initialized an array with the variable name "myArray" and stored it with integers ranging from 1 to 5.
  2. The for-each array method takes three parameters and applies a callback function on the array.
  3. This line; arr[index] = num * 2 multiplies the value of the current element by 2 and assigns the returned value to the current element's index.

Take note, the for-each array method does not return a new array; rather, it modifies the original array and returns it.

Output

[2, 4, 6, 8, 10]

What are for... in and for... of loops in JavaScript?

The for... in and for... of loops are very useful when it comes to iterating over iterable objects, iterable objects refers to any element that is capable of being looped over, common examples of iterables objects are arrays, strings, sets, etc.

The for... in and for... of are similar in how they iterate/move through objects, the main difference between them is shown on how they return values.

for... in loops

A for... in loop is useful when you need to extract the key(s)/properties from an object and it corresponding properties from the parent object, the for... in loop at times might iterate through an object in a manner that is different from the way it was defined in that particular object, let's take an example of a for... in loop in action.

let namesArray = [];

const studentScores = {
John: 60,
Dan: 53,
Tricia: 73,
Jamal: 45,
Jane: 52
}

for(const name in studentScores){
  namesArray.push(name);
}

console.log(namesArray);

In the example above, we have defined an object named studentScores that contains several student names and their corresponding scores, by using for... in, we were able to retrieve only the names of the students, which represent the keys of the object studentScores, and store them in an array by using the push() method.

Output

["John", "Dan", "Tricia", "Jamal", "Jane"]

for... of loops

The for... of loop is a special type of loop that iterates over the values of iterable objects such as arrays, strings, maps, e.t.c., for... of loops does not concern itself with the keys or properties of an object, rather it shows priorities on the values only, the for... of loop is unable to iterate over regular objects and will throw an error since they are not iterable. Let's take an example using the for.. of loop.

let numArray = [1,2,3,4,5]

for (const value of numArray) {
    console.log(value)
}

// Output = 1,2,3,4,5
In summary, the for... in and for... of loops are great way to loop through iterable objects, the main difference is a for... in loop returns the key of an Object while the for... of loop returns only the values of iterable objects.

What is an infinite loop and how can we avoid it?

An infinite loop refers to a loop that continues to run indefinitely; this occurs when a loop has no defined exit condition. Infinite loops are dangerous because they can crash your browser and lead to unwanted actions in your program.

// infinite loop sample
while (true) {
console.log("keep on running")
}
To prevent infinite loops in your program, always ensure that there is an exit condition defined within your loop.

Conclusion

Thank you very much for getting to the end of this article, loops in Javascript are important concept every developer needs to master as it is very valuable to creating a good and optimizable program, I believe with this article you would be able to understand the basics and intricacies of using loops in your program.

以上が初心者のための JavaScript ループ: 基本を学ぶの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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