강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)
insertAdjacentHTML() method는 이미 사용 중인 element를 다시 parsing 하지 않아서 'innerHtml'보다 작업이 덜 드므로 빠르다.
element.insertAdjacentHTML(position, text);
Position Option
ex)
const calcdisplayMovements = function (movements) {
containerMovements.innerHTML = '';
movements.forEach(function (mov, i) {
const type = mov > 0 ? 'deposit' : 'withdrawal';
const html = `
<div class="movements__row">
<div class="movements__type movements__type--deposit">${i + 1}
${type}</div>
<div class="movements__value">${mov}€</div>
</div>`;
containerMovements.insertAdjacentHTML('afterBegin', html);
});
};
calcdisplayMovements(account1.movements);
참고)
textContext와 innerHTML의 차이 :
map returns a new array containing the result of applying an operation on all original array elements
filter returns a new array containing the array elements that passed a specified test codition
reduce boils(reduce) all array elements down to one single value. ex) adding all element together
기존의 array 바꾸지 않음. 새로운 array를 return.
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
const eurToUsd = 1.1;
const movementsUSD = movements.map(mov => mov * eurToUsd);
console.log(movements);
console.log(movementsUSD);
const movementsUSDfor = [];
for (const mov of movements) movementsUSDfor.push(mov * eurToUsd);
console.log(movementsUSDfor);
const movementsDescriptions = movements.map(
(mov, i) =>
`Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdraw'} ${Math.abs(
mov
)}`
);
console.log(movementsDescriptions);
//['Movement 1: You deposited 200', 'Movement 2: You deposited 450', 'Movement 3: You withdraw 400',
//'Movement 4: You deposited 3000', 'Movement 5: You withdraw 650', 'Movement 6: You withdraw 130',
//'Movement 7: You deposited 70', 'Movement 8: You deposited 1300']
const deposits = movements.filter(function (mov) {
return mov > 0;
});
console.log(movements); //[200, 450, -400, 3000, -650, -130, 70, 1300]
console.log(deposits); //[200, 450, 3000, 70, 1300]
const depositsFor = [];
for (const mov of movements) if (mov > 0) depositsFor.push(mov);
console.log(depositsFor); // [200, 450, 3000, 70, 1300]
const withdrawals = movements.filter(mov => mov < 0);
console.log(withdrawals); //) [-400, -650, -130]
array를 return하는 것이 아니라 하나의 value를 return한다는 점 기억할 것!
acc = accumulator -> Snowball
const balance = movements.reduce((acc, cur) => acc + cur, 0);
console.log(balance); //3840
let balance2 = 0;
for (const mov of movements) balance2 += mov;
console.log(balance2); //3840
//Maximum value
const max = movements.reduce((acc, curr) => {
return acc > curr ? acc : curr;
}, movements[0]);
console.log(max); //3000
const eurToUsd = 1.1;
const totalDepositUSD = movements
.filter(mov => mov > 0)
.map(mov => mov * eurToUsd)
.reduce((acc, mov) => acc + mov, 0);
console.log(totalDepositUSD); //5522.000000000001
주의 사항)