-
forEach()JavaScript 2021. 6. 10. 21:44
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;Performs the specified action for each element in an array.
@param callbackfn A function that accepts up to three arguments.
forEach calls the callbackfn function one time for each element in the array.
@param thisArg An object to which the this keyword can refer in the callbackfn function.
If thisArg is omitted, undefined is used as the this value.
example.
1.
let numbers = [1, 2, 3, 4, 5, 6, 7]; numbers.forEach(function(num) { console.log(num); }) // same code numbers.forEach(num => console.log(num));2.
let fruits2 = ['🍎','🍒','🍌','🍉','🍓']; let fruits3 = ['🥝']; fruits2.forEach(fruit => fruits3.push(fruit)); console.log(fruits3); // [ '🥝', '🍎', '🍒', '🍌', '🍉', '🍓' ]3.
let sum = 0; let numbers2 = [20, 11, 33, 10, 7, 77]; numbers2.forEach(addTotal); function addTotal(num){ sum += num; } console.log(sum); // 158 // same code numbers2.forEach(number => sum += number) console.log(sum); // 1584.
let number3 = [20, 11, 33, 10, 7, 77, 5]; number3.forEach((number, index, array) => { array[index] = number * 2; }) console.log(number3); // [40, 22, 66, 20, 14, 154, 10]'JavaScript' 카테고리의 다른 글
reduce() (0) 2021.06.11 map() (0) 2021.06.10 3. async & await (0) 2021.06.10 2. Promise (0) 2021.06.10 1. callback function - Synchronous & Asynchronous (0) 2021.06.10