초보자를 위한 JavaScript 루프: 기본 사항 배우기
우울한 월요일인데, 당신은 직장에 있습니다. 월요일이 얼마나 우울한지 다들 아시죠? 상사가 당신에게 다가와서 "야, 주말 동안 받은 미개봉 이메일이 300통이나 있다. 각 이메일을 열어서 보낸 사람의 이름을 적고, 다 마친 후 이메일을 삭제해달라"고 말합니다.
이 작업을 수동으로 하려고 하면 매우 피곤해 보입니다. 다음으로 생각할 일은 아마도 Google에서 이 프로세스를 자동화하고 삶을 더 쉽게 만들어 줄 수 있는 소프트웨어를 찾는 것일 것입니다. 그렇죠?
글쎄요, 프로그래밍에서도 비슷한 상황이 있습니다. 완료될 때까지 반복적인 작업을 수행해야 하는 경우가 있습니다. 이 문제를 어떻게 해결합니까? JavaScript에는 루프라고 부르는 것이 있습니다. 루프를 사용하면 작업을 완료하는 데 필요한 코드 양을 줄여 반복되는 작업을 해결할 수 있습니다.
이 기사에서는 루프가 무엇인지, 어떻게 작동하는지, 프로그램에 루프를 적용하는 데 사용할 수 있는 다양한 방법에 대해 설명합니다.
루프란 무엇입니까?
루프는 JavaScript에서 반복 작업을 쉽게 수행하는 데 사용됩니다. 이는 true 또는 false를 반환하는 조건을 기반으로 합니다.
조건은 루프를 계속 실행하기 위해 전달해야 하는 표현식입니다. 지정된 조건이 참 값을 반환하면 루프가 실행되고 거짓 값을 반환하면 중지됩니다.
언제 루프를 사용해야 합니까?
루프는 반복적인 작업을 수행하는 데 유용합니다. 예를 들어, 루프를 사용하면 문제를 해결하는 데 필요한 코드가 단축됩니다. 시간을 절약하고 메모리 사용량을 최적화하며 유연성을 향상시킵니다.
루프의 진정한 의미는 코드 길이를 줄이고 반복을 제한하는 것 이상으로 확장됩니다. 배열, 개체 또는 기타 구조의 데이터로 작업할 때도 도움이 됩니다. 또한 루프는 반복 코드를 줄이고 코드 재사용성을 높여 코드 모듈성을 촉진하므로 프로젝트의 다양한 부분에서 사용할 수 있는 코드를 생성할 수 있습니다.
루프 유형
루프에는 진입 제어 루프와 종료 제어 루프라는 두 가지 주요 범주가 있습니다.
입력 제어 루프는 루프 본문을 실행하기 전에 "루프 입구"에서 조건을 평가합니다. 조건이 true이면 본문이 실행됩니다. 그렇지 않으면 몸이 움직이지 않습니다. for 및 while 루프는 입력 제어 루프의 예입니다.
종료 제어 루프는 테스트 조건보다 루프 본문에 초점을 맞춰 테스트 조건을 평가하기 전에 루프 본문이 적어도 한 번 실행되도록 합니다. 종료 제어 루프의 좋은 예는 do-while 루프입니다.
입력 제어 루프의 몇 가지 예를 살펴보겠습니다.
while 루프
while 루프의 구문은 다음과 같습니다.
while (condition) { // loop's body }
다음 목록에서는 while 루프의 기능을 설명합니다.
- while 루프는 괄호 안에 테스트 조건을 취합니다.
- 조건을 확인하여 합격, 불합격 여부를 확인하는 프로그램입니다.
- 루프 본문 내의 코드는 조건이 통과되는 한 실행됩니다.
- 테스트 조건이 실패하면 프로그램이 종료됩니다.
아래에서 while 루프에 대한 실제 예를 살펴보겠습니다.
let arr = []; let i = 1; let number = 5; while (i <= number) { arr.push(i) i++ }
console.log(arr)
- 위의 코드 조각은 "arr", "i" 및 "num" 변수를 초기화합니다.
- "arr" 변수는 테스트 조건을 통과한 값을 보유하는 배열입니다.
- "i" 변수는 각 반복 후 각 증분을 추적합니다.
- "number" 변수는 각 반복 후에 "i" 값을 해당 값(5)과 비교합니다.
- 루프 본문 내의 코드는 "i"가 "number"보다 작거나 같은 한 각 반복 후에 "i"의 각 값을 배열에 푸시합니다.
- 현재 "i" 값이 조건을 만족하지 않으면 "i" 값이 "number"인 6보다 큰 경우 루프 실행이 중지됩니다.
push() 메소드는 배열의 끝에 새 항목을 추가하는 내장 JavaScript 함수입니다.
출력
[1, 2, 3, 4, 5]
do-while 루프
do-while 루프는 while 루프와 매우 유사합니다. while과 do-while루프의 주요 차이점은 do-while 루프는 루프의 조건을 평가하기 전에 적어도 한 번은 코드 실행을 보장한다는 것입니다. 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);
이제 이 코드 조각을 분석해 보겠습니다.
- We initialized the "i" and "num" variables.
- The console logs in the value of "i" (1) before evaluating the loop's condition.
- The condition is checked, and the value of "i" increments with +1 after each iteration.
- 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?
- We initialized the "i" and "num" variables with values of 5 and 4, respectively.
- The condition checks if the value of "i" is less than "num".
- If true, it logs in each respective value.
- 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.
- First, we've initialized the counter variable "i" with a value of zero.
- Next, we've created the conditional statement that would keep the code running.
- We compared the value of "i" with 100, if it passes this test, "Hello World" is logged.
- This process repeats while the counter increases with +1 after each iteration.
- 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:
- We initialized an array with the variable name "myArray" and stored it with integers ranging from 1 to 5.
- The for-each array method takes three parameters and applies a callback function on the array.
- 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.
