티스토리 뷰
//비전공자가 혼자 공부하는 공간입니다
.forEach 가 function을 각 array element (배열 요소)에 실행시킬 수 있다면
결국 for loop (반복문)과 같은 역할을 하는 것일까? 챗지피티에 물어봐야겠다
🆀 Array.prototype.forEach() runs the same thing as the for loop with array?
🅰 Yes, you can achieve the same result with a forEach() method and a for loop.
The forEach() method is a higher-order function that takes a callback function as an argument, and calls that function once for each element in the array.
The forEach() method is essentially a shorthand for a for loop that loops over each element in the array and performs some action.
let numbers = [1, 2, 3, 4, 5];
// Using forEach() method
numbers.forEach(function(element) {
console.log(element);
});
// Output:
// 1
// 2
// 3
// 4
// 5
// Using for loop
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Output:
// 1
// 2
// 3
// 4
// 5
이렇게 예시도 주었다
해당 표는 긱스포긱스를 참고하였다
https://www.geeksforgeeks.org/difference-between-foreach-and-for-loop-in-javascript/
Difference between forEach and for loop in Javascript - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
그런데 왜 Array.prototype.forEach() 에서 'prototype'을 생략하기도 하는 걸까 (맨날 왜왜 하면서 궁금해하다가 도대체 포트폴리오는 언제 완성할까 싶다)
-prototype을 생략하지 않아야 할 때
1️⃣ Adding a custom method to all arrays:
Array.prototype.sum = function() {
let result = 0;
this.forEach(function(element) {
result += element;
});
return result;
};
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.sum()); // 15
2️⃣ Debugging and inspecting an object:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.__proto__); // Array.prototype
console.log(Array.prototype); // Array.prototype
3️⃣ Creating a custom object type:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Car.prototype.getFullName = function() {
return this.make + " " + this.model + " " + this.year;
};
let myCar = new Car("Toyota", "Camry", 2022);
console.log(myCar.getFullName()); // "Toyota Camry 2022"
//비전공자가 혼자 공부하는 공간입니다
'JavaScript' 카테고리의 다른 글
[자바스크립트 기본 개념] 함수의 정의와 종류 (0) | 2024.09.19 |
---|---|
[자바스크립트 기본 개념] 변수 (0) | 2024.08.30 |
[발표 스터디] this에 대해 설명하기 (0) | 2023.04.17 |
자바스크립트로 html 코드 생성하기 (0) | 2023.02.03 |
눈 뜨자마자 어플로 퀴즈 풀기 (0) | 2023.01.28 |
- Total
- Today
- Yesterday
- DOM제어
- 즉시실행함수
- CSS게임
- vanillajs
- CSSDiner
- CSS
- 비전공자
- CSS선택자
- 로컬스토리지오류
- DOMapi
- 상태변수
- DOM자바스크립트
- translateX
- 자바스크립트
- :nth-child
- 프론트엔드독학
- 코딩독학
- 이벤트핸들링
- 변수스코프
- VirtualDom
- 가상돔
- dom조작
- 체크박스오류
- labelfor
- 캐시오류
- 논리부정연산자
- 프로그래밍독학
- 리액트
- 화살표함수
- JavaScript
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |