Rumah > Artikel > hujung hadapan web > Gelung JavaScript untuk Pemula: Pelajari Asas
Hari Isnin yang suram, dan anda sedang bekerja. Kita semua tahu betapa menyedihkan hari Isnin, bukan? Bos anda menghampiri anda dan berkata, "Hei, saya ada 300 e-mel yang belum dibuka yang kami terima pada hujung minggu. Saya mahu anda membuka setiap satu, tulis nama pengirim dan padamkan e-mel itu sebaik sahaja anda selesai."
Tugas ini kelihatan sangat memenatkan jika anda cuba melakukannya secara manual. Perkara seterusnya dalam fikiran anda mungkin untuk pergi ke Google dan mencari perisian yang boleh mengautomasikan proses ini dan menjadikan hidup anda lebih mudah, bukan?
Nah, kami mempunyai situasi yang sama dalam pengaturcaraan. Ada kalanya anda perlu melakukan tugasan berulang sehingga selesai. Bagaimana anda menyelesaikan masalah ini? Dalam JavaScript, kami mempunyai apa yang kami rujuk sebagai gelung. Gelung membolehkan kami menyelesaikan tugasan berulang dengan mengurangkan jumlah kod yang diperlukan untuk menyelesaikan tugasan.
Dalam artikel ini, kita akan membincangkan apa itu gelung, cara ia berfungsi dan pelbagai kaedah yang boleh kita gunakan untuk mengaplikasikannya dalam atur cara kita.
Gelung digunakan dalam JavaScript untuk melakukan tindakan berulang dengan mudah. Ia adalah berdasarkan syarat yang mengembalikan benar atau salah.
Syarat ialah ungkapan yang mesti diluluskan untuk memastikan gelung berjalan. Gelung berjalan apabila syarat yang ditentukan mengembalikan nilai benar dan berhenti apabila ia mengembalikan nilai palsu.
Gelung berguna untuk menjalankan tugas berulang. Contohnya, menggunakan gelung memendekkan kod yang diperlukan untuk menyelesaikan masalah. Ia menjimatkan masa, mengoptimumkan penggunaan memori dan meningkatkan fleksibiliti.
Kepentingan sebenar gelung melangkaui mengurangkan panjang kod dan mengehadkan pengulangan. Mereka juga membantu apabila bekerja dengan data dalam tatasusunan, objek atau struktur lain. Selain itu, gelung menggalakkan modulariti kod dengan mengurangkan kod berulang dan meningkatkan kebolehgunaan semula kod, yang memungkinkan untuk membuat kod yang boleh digunakan dalam bahagian yang berlainan dalam projek anda.
Terdapat dua kategori utama gelung: gelung terkawal kemasukan dan gelung terkawal keluar.
GelungKawalan kemasukan menilai keadaan di "pintu masuk gelung" sebelum melaksanakan badan gelung. Jika keadaan itu benar, badan berjalan. Kalau tak, badan tak lari. Gelung for dan while ialah contoh gelung terkawal kemasukan.
Kawalan keluar gelung memfokuskan pada badan gelung atas keadaan ujian, memastikan bahawa badan gelung dilaksanakan sekurang-kurangnya sekali sebelum menilai keadaan ujian. Contoh yang baik bagi gelung terkawal Keluar ialah gelung do-while.
Mari kita periksa beberapa contoh gelung terkawal kemasukan:
Gelung sementara mempunyai sintaks berikut.
while (condition) { // loop's body }
Senarai berikut menerangkan kefungsian gelung sementara:
Di bawah, mari kita ambil contoh praktikal pada gelung while:
let arr = []; let i = 1; let number = 5; while (i <= number) { arr.push(i) i++ }
console.log(arr)
Kaedah push() ialah fungsi JavaScript terbina dalam yang menambahkan item baharu pada penghujung tatasusunan.
Output
[1, 2, 3, 4, 5]
Do-whileloop hampir menyerupai gelung while; perbezaan utama antara while dan do-whileloop ialah gelung do-while memastikan pelaksanaan kod sekurang-kurangnya sekali sebelum menilai keadaan gelung, gelung do-while mempunyai sintaks berikut di bawah.
do { // loop's body } while (//condition)
Do-while ialah contoh terbaik bagi gelung terkawal keluar. Ini terletak pada hakikat bahawa gelung terkawal keluar memberi keutamaan kepada badan gelung sebelum keadaan ujian, sekarang mari kita mendalami contoh kod praktikal menggunakan gelung do-while.
Contoh:
let i = 1; let num = 5; do { console.log(i); i++; } while (i <= num);
Sekarang mari kita pecahkan coretan kod ini:
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?
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.
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.
Output
Hello World Hello World Hello World ... //repeated 97 more times making it 100 "Hello World" in total ...
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.
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:
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]
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.
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"]
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.
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.
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.
Atas ialah kandungan terperinci Gelung JavaScript untuk Pemula: Pelajari Asas. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!