Function ์ฐ์ตํด์ฆ 4
1. ํจ์์์ setInterval ์ฌ์ฉ
1์ด๋ง๋ค 'Hello'๋ฅผ 3๋ฒ ์ถ๋ ฅํ๋ printHello ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
setInterval๊ณผ clearInterval ์ฌ์ฉ
function printHello() {
let count = 0;
const id = setInterval(function() {
console.log('Hello');
count++;
if(count === 3) clearInterval(id);
}, 1000);
}
printHello();
2. ํจ์์์ Date ๊ฐ์ฒด ์ฌ์ฉ
ํ์ฌ ์ฐ๋๋ฅผ ๋ฐํํ๋ getCurrentYear ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
new Date().getFullYear() ์ฌ์ฉ
function getCurrentYear() {
return new Date().getFullYear();
}
console.log(getCurrentYear());
3. ํจ์์์ Math.random ์ฌ์ฉ
0 ์ด์ 1 ๋ฏธ๋ง์ ๋์๋ฅผ ๋ฐํํ๋ getRandom ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
Math.random() ์ฌ์ฉ
function getRandom() {
return Math.random();
}
console.log(getRandom());
4. ํจ์์์ Math.floor ์ฌ์ฉ
0 ์ด์ 10 ๋ฏธ๋ง์ ์ ์๋ฅผ ๋ฐํํ๋ getRandomInt ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
Math.floor(Math.random() * 10) ์ฌ์ฉ
function getRandomInt() {
return Math.floor(Math.random() * 10);
}
console.log(getRandomInt());
5. ํจ์์์ ๋ฐฐ์ด์ ๊ธธ์ด ๋ฐํ
๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ๋ฐํํ๋ getLength ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
arr.length ์ฌ์ฉ
function getLength(arr) {
return arr.length;
}
console.log(getLength([1,2,3]));
6. ํจ์์์ ๋ฐฐ์ด์ ๋ง์ง๋ง ๊ฐ ๋ฐํ
๋ฐฐ์ด์ ๋ง์ง๋ง ๊ฐ์ ๋ฐํํ๋ getLast ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
arr[arr.length-1] ์ฌ์ฉ
function getLast(arr) {
return arr[arr.length-1];
}
console.log(getLast([1,2,3]));
7. ํจ์์์ ๋ฐฐ์ด์ ๋ชจ๋ ๊ฐ ์ถ๋ ฅ
๋ฐฐ์ด์ ๋ชจ๋ ๊ฐ์ ํ ์ค์ฉ ์ถ๋ ฅํ๋ printAll ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
forEach ์ฌ์ฉ
function printAll(arr) {
arr.forEach(x => console.log(x));
}
printAll([1,2,3]);
8. ํจ์์์ ๋ฐฐ์ด์ ์ง์๋ง ์ถ๋ ฅ
๋ฐฐ์ด์์ ์ง์๋ง ์ถ๋ ฅํ๋ printEvens ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
forEach์ if๋ฌธ ์ฌ์ฉ
function printEvens(arr) {
arr.forEach(x => { if(x % 2 === 0) console.log(x); });
}
printEvens([1,2,3,4]);
9. ํจ์์์ ๋ฐฐ์ด์ ํฉ์ด ์ง์์ธ์ง ๋ฐํ
๋ฐฐ์ด์ ํฉ์ด ์ง์๋ฉด true, ์๋๋ฉด false๋ฅผ ๋ฐํํ๋ isSumEven ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
reduce๋ก ํฉ์ ๊ตฌํ ๋ค % 2 === 0 ์ฒดํฌ
function isSumEven(arr) {
return arr.reduce((a,b)=>a+b,0) % 2 === 0;
}
console.log(isSumEven([1,2,3]));
10. ํจ์์์ ๋ฐฐ์ด์ ๋ชจ๋ ๊ฐ 2๋ฐฐ๋ก ๋ฐํ
๋ฐฐ์ด์ ๋ชจ๋ ๊ฐ์ 2๋ฐฐ๋ก ๋ง๋ ์ ๋ฐฐ์ด์ ๋ฐํํ๋ doubleArray ํจ์๋ฅผ ์์ฑํ์์ค.
// ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์
map ์ฌ์ฉ
function doubleArray(arr) {
return arr.map(x => x * 2);
}
console.log(doubleArray([1,2,3]));