let count = 0;
const timer = setInterval(function () {
console.log(count);
if (++count > 4) clearInterval(timer);
}, 300);
// ์คํ ๊ฒฐ๊ณผ
// 0
// 1
// 2
// 3
// 4
let count = 0;
const cbFunc = function () {
console.log(count);
if (++count > 4) clearInterval(timer);
}
let timer = setInterval(cbFunc, 300);
// ์คํ ๊ฒฐ๊ณผ
// 0
// 1
// 2
// 3
// 4
const newArr = [10, 20, 30].map(function (currentValue, index) {
console.log(currentValue, index);
return currentValue + 5;
});
console.log(newArr);
// ์คํ ๊ฒฐ๊ณผ
// 10 0
// 20 1
// 30 2
// [15, 25, 35]
const newArr = [10, 20, 30].map(function (index, currentValue) {
console.log(index, currentValue);
return currentValue + 5;
});
console.log(newArr);
// ์คํ ๊ฒฐ๊ณผ
// 10 0
// 20 1
// 30 2
// [5, 6, 7]
Array.prototype.map = function (callback, thisArg) {
let mappedArr = [];
for (let i = 0; i < this.length; i++) {
const mappedValue = callback.call(thisArg || window, this[i], i, this);
mappedArr[i] = mappedValue;
}
return mappedArr;
}
const result = [10, 20, 30].map(function (value, index) {
console.log(this, value, index);
return value + 100;
});
console.log(result);
// ์คํ ๊ฒฐ๊ณผ
// Window 10 0
// Window 20 1
// Window 30 2
// [110, 120, 130]
const anotherResult = [10, 20, 30].map(function (value, index) {
console.log(this, value, index);
return value + 100;
}, [1, 2, 3]);
console.log(anotherResult);
// ์คํ ๊ฒฐ๊ณผ
// [1, 2, 3] 10 0
// [1, 2, 3] 20 1
// [1, 2, 3] 30 2
// [110, 120, 130]
์ฒ์ ์์ ๋ฅผ ๋ดค์ ๋์๋ this๋ฅผ ๋ค๋ฅด๊ฒ ์ง์ ํ๋ฉด map์ ์คํ ๊ฒฐ๊ณผ๋ ๋ค๋ฅด๊ฒ ๋์ค๋ ๊ฒ์ธ ์ค ์์๋๋ฐ, ์คํ์ ํด๋ณด๊ณ ๊ทธ๋ ์ง ์์ ๊ฒฐ๊ณผ๊ฐ ๋์์ ์กฐ๊ธ ๋นํฉ ํ๋ค. ๊ณฐ๊ณฐํ ์๊ฐ์ ํด๋ณด๋ thisArg๋ก ๋๊ธฐ๋ ๊ฒ์ ์ฝ๋ฐฑ ํจ์์ this๋ฅผ ์ง์ ํ๋ ๊ฒ์ด์ง map ๋ฉ์๋์ this๋ฅผ ์ง์ ํ๋๊ฒ ์๋๊ธฐ ๋๋ฌธ์ ๊ฒฐ๊ณผ ๊ฐ์๋ ์ํฅ์ด ์๋๊ฒ ๋ง๋ค.
const cbFunc = function () {
console.log(this);
};
setTimeout(cbFunc, 300);
// ์คํ ๊ฒฐ๊ณผ
// Window
const arr = [1, 2, 3, 4, 5];
arr.forEach(cbFunc);
// ์คํ ๊ฒฐ๊ณผ
// Window
// Window
// Window
// Window
// Window
arr.forEach(cbFunc, arr);
// ์คํ ๊ฒฐ๊ณผ
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4, 5]
document.body.innerHTML += '<button id="a">ํด๋ฆญ</button>';
document.body.querySelector('#a')
.addEventListener('click', cbFunc);
// ์คํ ๊ฒฐ๊ณผ
// <button id="a">ํด๋ฆญ</button>