티스토리 뷰

//비전공자가 혼자 공부하는 공간입니다

 

 

.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"

 

 

//비전공자가 혼자 공부하는 공간입니다