const num = 1.123456789;
console.log(num.toFixed(5));
//출력 1.12346
toFixed() : ()안에 든 숫자만큼 소숫점 단위를 끊는다.(단 끊는 단위 미만은 반올림)
const num = 1.123456789;
console.log(typeof num.toString());
//출력 string
toString() : 문자열을 반환 함수
const str = "Abcd";
console.log(`${str} charAt("A"): ${str.charAt(0)}`);
//출력 Abcd charAt("A") : A
charAt() : () 안에 들어가는 문자열 반환
const str = "Abcd";
console.log(`${str} : ${str.concat("e")}`);
//출력 Abcd : Abcde
concat() : () 안에 들어가는 문자 합치기
const str = "Abcd";
console.log(`${str} : ${str.endsWith("D")}`);
//출력 Abcd : false
endsWith() : () 안에 들어가는 문자가 str 문자열 끝과 동일하는지 확인하는 함수
const str = "Abcd";
console.log(`${str} : ${str.startsWith("A")}`);
//출력 Abcd : true
startsWith() : () 안에 들어가는 문자가 str 문자열 처음과 동일하는지 확인하는 함수
const str = "Abcd";
console.log(`${str} : ${str.includes("Ab")}`);
//출력 Abcd : true
includes() : () 안에 들어가는 문자가 str 에 포함되는지 확인하는 함수
const str = "Abcd";
console.log(`${str} : ${str.indexOf("d")}`);
//출력 Abcd : 3
indexOf() : () 안에 들어가는 문자가 몇번째 배열에 있는가 반환하는 함수
const str = "Abcd";
console.log(`${str} : ${str.normalize()}`);
//출력 Abcd : Abcd
normalize() : 문자열을 유니코드 정규화 방식(Unicode Normalization Form)에 따라 정규화된 형태로 반환
const str = "Abcd";
console.log(`${str} : ${str.padStart(8)}`);
//출력 Abcd : Abcd:
padStart() : 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환
const str = "Abcd";
console.log(`${str} : ${str.repeat(5)}`);
//출력 Abcd : AbcdAbcdAbcdAbcdAbcd
repeat() : () 안에 들어가는 수 만큼 문자열 반복
const str = "Abcd";
console.log(`${str} : ${str.replace("cd", "ef")}`);
//출력 Abcd : Abef
replace() : 문자열 대체
const str = "Abcd";
console.log(`${str} : ${str.slice(1,3)}`);
//출력 Abcd : bc
slice() : slice(start,end) start 부분까지 지우고 end 문자열까지 출력
console.log("나는 학교에 갑니다.".split(" "));
//출력 (3) ['나는', '학교에', '갑니다.']
split() : String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.
console.log("나는 학교에 갑니다.".split(1));
//출력 Abcd : bcd
split() : () 안에 든 숫자부터 문자열 반환
const str = "Abcd";
console.log(`${str} : ${str.toLowerCase()}`);
console.log(`${str} : ${str.toUpperCase()}`);
//출력 Abcd : abcd
// Abcd : ABCD
toLowerCase() : 소문자 반환
toUpperCase() : 대문자 반환
console.log(`${str} : ${" abcd ".trim()}`);
//출력 Abcd : abcd
trim() : 문자열 양 끝의 공백을 제거하고 원본 문자열을 수정하지 않고 새로운 문자열을 반환
const arr = ["A", "B", "c", "d"];
console.log(`${arr} concat("e") : ${arr.concat("e", "f")}`);
console.log(`${arr} concat("e") : ${arr.concat(["g"])}`);
//출력 A,B,c,d concat("e") : A,B,c,d,e,f
//출력 A,B,c,d concat("e") : A,B,c,d,g
concat() : () 안에 있는 문자열 또는 배열 붙이기
const arr = ["A", "B", "c", "d"];
console.log(`${arr} : ${arr.copyWithin(3, 1)}`);
//출력 A,B,c,d : A,B,c,B
copyWithin() : 배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환
const arr = ["A", "B", "c", "d"];
console.log(`${arr} : ${arr.fill("a")}`);
//출력 A,B,c,B : a,a,a,a
fill() : () 안에 있는 문자를 문자열로 채움
console.log(
[
["a", "b"],
["c", "d"],
].flat()
);
//출력 (4) ['a', 'b', 'c', 'd']
flat() : 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성한다
const arr = ["A", "B", "c", "d"];
console.log(`${arr} pop() : ${arr.pop()}`);
console.log(arr);
//출력 A,B,c,d pop() : d
// (3) ['A', 'B', 'c']
pop() : 마지막 배열 빼내기
const arr = ["A", "B", "c", "d"];
console.log(`${arr} push("g") : ${arr.push("g")}`);
console.log(arr);
//출력 A,B,c,d push("g") : 5
// (5) ['A', 'B', 'c', 'd', 'g']
push() : 배열에 집어넣기
const arr = ["A", "B", "c", "d"];
console.log(`${arr} : ${arr.join(" ")}`);
//출력 A,B,c,d : A B c d
join() : 배열의 모든 요소를 연결해 하나의 문자열로 만든다.
const arr = ["A", "B", "c", "d"];
console.log(`${arr} : ${arr.reverse()}`);
//출력 A,B,c,d : d,c,B,A
reverse() : 문자열 뒤집기
const arr = ["A", "B", "c", "d"];
arr.forEach(element => console.log(element));
//출력 A
// B
// C
// D
forEach() : 주어진 함수를 배열 요소 각각에 대해 실행
const arr = ["A", "B", "c", "d"];
const predicate1 = (value) => {
return value.charCodeAt(0) > 97;
};
console.log(arr.filter(predicate1));
//출력 (2) ['c', 'd']
filter() : 조건을 필터링해서 배열 반환
const arr = ["A", "B", "c", "d"];
console.log(arr.map((value) => value));
//출력 (4) ['A', 'B', 'c', 'd']
map() : 배열의 요소를 반환
const array1 = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
//출력 10
reduce() : 요소 합치기
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
//출력 true
every() : 모든 요소가 조건에 부합하는지
const array = [1, 2, 3, 4, 5];
// Checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
//출력 true
some() : 하나의 오소라도 조건에 부합하는지
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
//출력 12
find() : 조건 부합하는 요소 찾기(만족하는 첫번쨰 요소값 반환)
const obj = {
key: "value",
func: (value) => value,
array: [1, 2, 3, 4],
obj: {
key: "value1",
},
};
console.log(obj.key);
console.log(obj.obj.key);
console.log(obj.func());
//출력 value
// value1
// undefined
obj() : 객체 반환
console.log(Math.PI); //3.14
console.log(Math.abs(-1)); //절댓값
console.log(Math.ceil(1.2)); //올림
console.log(Math.floor(1.5)); //내림
console.log(Math.round(1.5)); //반올림
console.log(Math.pow(2, 3)); //2^3=8
console.log(Math.max(1, 2, 3)); //3
console.log(Math.min(1, 2, 3)); //1
console.log(Math.floor(Math.random() * 10)); //0~9 사이의 난수
Math() : 수학관련 함수
console.log(Date.now()); //1970년 1월1일 12시 정각부터 ms 단위로 숫자를 리턴
const myDate = new Date("2020-11-10 00:00:00");
console.log(myDate); //Date 클래스에 넣은 값을 리턴
console.log(myDate.getFullYear()); //Date 클래스에 넣은 year 값 리턴
console.log(myDate.getFullMonth()); //Date 클래스에 넣은 month-1 값 리턴
console.log(myDate.getFullDate()); //Date 클래스에 넣은 day 값 리턴
console.log(myDate.getFullDay()); //Date 클래스에 넣은 요일 값 리턴
Date() : 날짜관련 함수
const 부산시 = {
부산진구: {
범천동: ["범일로 192번길", "범일로 180번길"],
},
};
console.log(부산시.부산진구.범천동);
//출력 (2) ['범일로 192번길', '범일로 180번길']
const 부산시 = {
부산진구: {
범천동: ["범일로 192번길", "범일로 180번길"],
},
};
console.log(부산시.동의구?.범천동);
</script>
// console.log 안에 ? 가 올시 에러가 뜨지 않고 undefined 가 나옴.
const 부산시 = { key: "value" };
let temp;
if (Date.now() % 2 == 0) {
temp = 부산시;
}
console.log(temp?.key);
//출력 undefined 또는 value
// Date.now() 에 짝수또는 홀수 값이 오면서
// 짝수일경우 value 를 출력 홀수일 경우 undefined 출력
const 부산시 = { key: "value" };
let temp;
if (Date.now() % 2 == 0) {
temp = 부산시;
}
console.log(temp.key);
//출력 value 또는 에러
const myFunc = () => {
console.log("확인");
myFunc();
};
myFunc();
//출력 확인 무한 반복
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>시계</h1>
<div>
<span id="hour"></span> <!--span선언시 가로(줄단위)로 출력, div선언시 세로(박스)로 출력 -->
<span id="minute"></span>
<span id="second"></span>
</div>
</body>
<script>
const getClock = () => {
const myDate = new Date();
const hour = document.getElementById("hour");
hour.innerText = myDate.getHours() + "시"; // 화면에 '시' 출력
const minute = document.getElementById("minute");
minute.innerText = myDate.getMinutes() + "분";
const second = document.getElementById("second");
second.innerText = myDate.getSeconds().toString().padStart(2, "0") + "초";//toString()을 통해
//문자열로 변환 후 padStart()를 통해 초 앞에 0을 추가함.
};
setInterval(getClock, 1000);//1초마다 업데이트
</script>
</html>
- setInterval() 사용법
웹페이지의 특정 부분을 주기적으로 업데이트해줘야 하거나, 어떤 API로 부터 변경된 데이터를 주기적으로 받아와야 하는 경우가 있는데요. 이럴 때는 자바스크립트의 setInterval() 함수를 사용할 수 있습니다.
setInterval() 함수는 어떤 코드를 일정한 시간 간격을 두고 반복해서 실행하고 싶을 때 사용합니다. 함수 API는 setTimeout() 함수와 대동소이한데요. 첫번째 인자로 실행할 코드를 담고 있는 함수를 받고, 두번째 인자로 반복 주기를 밀리초(ms) 단위로 받습니다.