함수 표현식
const hello = function ddd(){
console.log('안녕하세요.JavaScript!');
}
hello();
화살표 함수
- ECMA Script6에 추가된 문법
- function 키워드를 사용하여 함수를 만드는 것보다 간단하게 표현
- 화살표 함수는 항상 익명
매개변수가 없는 경우
const hello = () => {
console.log('안녕하세요. JavaScript!');
}
const hello = () => console.log('안녕하세요. JavaScript!');
const func1 = () => console.log('안녕하세요 JavaScript!')
func1();
매개변수가 있는 경우
const sum = function(x,y){
console.log(`두 수의 합: ${x + y}`);
}
const sum = (x, y) => consol.log(`두 수의 합: ${x + y}`);
const func2 =(x, y) => console.log(`두 수의 합: ${x + y}`);
func2(10, 3);
const func3 = (x) => x * x;
const result = func3(4);
console.log(`4의 제곱: ${result}`);
리턴값이 있는 경우
const result = function(x, y){
let sum = 0;
for(let i=x; i<=y; i++){
sum += i;
}
return sum;
}
const result = (x,y) => {
let sum = 0;
for(let i=x; i<=y; i++){
sum += i;
}
return sum;
}
매개변수가 하나일때는 괄호() 안써도 됨!
또한 다른 소스 없고 리턴만 쓸때도
리턴생략가능
const pow = x => x * x;
const func4 = (x, y) => {
let sum = 0;
for(let i=x; i<=y; i++){
sum += i;
}
return sum;
}
const total = func4(1, 100);
console.log(total);
const age = 20;
const isAdult = (age > 18) ? () => console.log('you are adult!') : () => onsole.log('you are not adult');
VSCode에서 nodejs로 js간단하게 실행하는법
구글에 nodejs 검색해서 설치하고
vscode 껐다 키고
터미널에
node 자바스크립트파일.js 치면 됨
https://nodejs.org/ko/download/
다운로드 | Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
객체(Object)
프로퍼티(property)
- 이름과 값으로 구성된 정렬되지 않은 집합
- 프로퍼티는 함수도 저장할 수 있음(프로퍼티 메소드)
const unserid = {'no':1, 'name':'apple','age':20,'gender':'girl'}
객체를 생성하는 방법
1.리터럴 표기법
const 객체명 = {
프로퍼티명1: 값1,
프로퍼티명2: 값2,
...
프로퍼티명n: function(){
프로퍼티 메소드가 호출되면 실행할 문장;
...
}
}
const dog = {
name: '루시',
age: 12,
color: 'white',
weight: 3.5,
birthday: '20091210',
getBirthday: function(){ // 프로퍼티 메소드
return this.birthday;
}
}
console.log(dog.name);
console.log(dog.age);
console.log(dog.color);
console.log(dog.weight);
console.log(dog['name']);
console.log(dog['age']);
console.log(dog['color']);
console.log(dog['weight']);
--결과값--
루시
12
white
3.5
for(let i in dog){
console.log(`i: ${i}, dog[i]: ${dog[i]}`);
}
--결과값--
i: name, dog[i]: 루시
i: age, dog[i]: 12
i: color, dog[i]: white
i: weight, dog[i]: 3.5
i: birthday, dog[i]: 20091210
i: getBirthday, dog[i]: function(){ // 프로퍼티 메소드
return this.birthday;
}
console.log(dog.getBirthday());
console.log(dog.getBirthday);
--결과값--
20091210
[Function: getBirthday]
2. 생성자를 이용
function 생성자명(매개변수1, 매개변수2 ..){
this.프로퍼티명1 = 값1;
this.프로퍼티명2 = 값2;
...
this.프로퍼티명n: function(){
프로퍼티 메소드가 호출되면 실행할 문장;
...
}
}
const 객체명 = new 생성자명(값1, 값2 ..);
- new 연산자를 사용하여 객체를 생성하고 초기화 할 수 있음
- 객체를 생성할 때 사용하는 함수를 생성자라고 함
- 새롭게 생성되는 객체를 초기화하는 역할
- 같은 형태의 객체를 여러개 생성할 때 유리
function Dog(name, color){
this.name = name;
this.color = color;
this.play = function(){
return `${this.name}는 놉니다`;
}
//aaaa=20;이렇게도 입력가능
}
const Rucy = new Dog('rucy','black');
console.log(Rucy.name);
console.log(Rucy.color);
console.log(Rucy.play());
--결과값--
rucy
black
rucy는 놉니다
const PPomi = new Dog('bbomi','white');
console.log(PPomi.name);
console.log(PPomi.color);
console.log(PPomi.play());
--결과값--
bbomi
white
bbomi는 놉니다
3. 클래스이용
const 클래스명 = class {
constructor(매개변수1, 매개변수2 ..){
this.프로퍼티명1 = 값1;
this.프로퍼티명2 = 값2;
...
}
메소드명(매개변수1, 매개변수2 ..){
프로퍼티 메소드가 호출되면 실행할 문장;
...
}
}
const 객체명1 = new 클래스명(값1, 값2..);
const 객체명2 = new 클래스명(값1, 값2..);
- ECMA Script6에 추가된 객체 생성 방법
- 내부적으로 생성자를 이용한 객체 생성 방법과 동일하게 작동
상속
- 자바스크립트는 프로토타입 기반의 객체 지향 언어(클래스 기반의 객체지향 언어와 다름)
- 현재 존재하고 있는 객체의 프로토타입을 사용하여 해당 객체를 복사하고 재사용하는 것
const Dog2 = class {
constructor(name, age, color){ //생성자
this.name = name;
this.age = age;
this.color = color;
}
변수선언가능;
메소드는 따로 써줘야함
play(){
return `${this.name}는 즐겁게 놉니다`
}
}
const PPory = new Dog2('ppori',4,'white');
console.log(PPory.name);
console.log(PPory.age);
console.log(PPory.color);
console.log(PPory.play());
--결과값--
ppori
4
white
ppori는 즐겁게 놉니다
✔ 프로토타입(prototype)
- 모든 객체는 프로토타입이라는 객체를 가지고 있음
- 모든 객체는 프로토타입으로부터 프로퍼티와 프로퍼티 메소드를 상속받음
- 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며 상속되는 정보를 제공하는 객체를 프로토타입이라고 함
const dog = new Dog(); // Dog.prototype, Object.prototype
function Dog(color, name, age){
this.color = color;
this.name = name;
this.age = age;
}
const HooChuChu = new Dog('white','후츄츄',13);
console.log(`name: ${HooChuChu.name}`);
console.log(`name: ${HooChuChu.color}`);
console.log(`name: ${HooChuChu.age}`);
HooChuChu.family = '포메';
HooChuChu.getFamily = function(){
return this.family;
}
console.log(`종: ${HooChuChu.family}`);
console.log(HooChuChu.getFamily());
const PPomi = new Dog('black','ppomi',4);
console.log(`name: ${PPomi.name}`);
console.log(`color: ${PPomi.color}`);
console.log(`age: ${PPomi.age}`);
console.log(`species: ${PPomi.family}`);
//console.log(PPomi.getFamily());
//console.log(PPomi.getFamily());
를 쓰면 에러 발생
후추추의 프토로타입을 수정한거지 뽀미는
수정한게 없어서 그대로 Dog과 형태가 같기때문
--결과값--
name: 후츄츄
name: white
name: 13
종: 포메
포메
name: ppomi
color: black
age: 4
species: undefined
Dog타입의 인스턴스 HooChuChu가 생성되면서
Dog의 프로토타입이 HooChuChu에도 복붙
후추추 만의 고유한 프토로타입이 만들어진셈
형태는 Dog과 똑같으나
후추추의 프토로타입을 수정하면
Dog의 프로토타입은 변경안되고 후추추 고유의 프로토타입만 변경
Dog은 전역변수같은느낌 후추추는 지역변수?
그렇다면 Dog타입의 프로토타입을 변경해보자
Dog.prototype.birthday = '20091210';
Dog.prototype.run = function(){
return this.name + 'is running';
}
const Pory = new Dog('brown','Pory',5);
console.log(`name: ${Pory.name}`);
console.log(`color: ${Pory.color}`);
console.log(`age: ${Pory.age}`);
console.log(`birthday: ${Pory.birthday}`);
console.log(Pory.run());
--결과값--
name: Pory
color: brown
age: 5
birthday: 20091210
Poryis running
Dog.prototype.birthday 이런식으로 .prototype. 을 사용해서 추가가능
Math 객체
수학에서 자주 사용하는 상수와 함수들을 미리 구현한 자바스크립트 표준 내장 객체
min(): 가장 작은 수를 리턴. 매개변수가 전달되지 않으면 -Infinity를 리턴. 비교할 수 없는 값이 포함되어 있으면 NaN을 리턴
max(): 가장 큰 수를 리턴
round(): 소수점 첫번째 자리에서 반올림하여 그 결과를 리턴
floor(): 버림
ceil(): 소수점 올림
random(): 0보다 크거나 같고 1보다 작은 무작위 소수를 리턴
console.log(Math.min());
console.log(Math.max());
console.log(Math.min(1,10, -10, 1000, 0));
console.log(Math.min(1,10, -10, 1000, '마이너스십'));
console.log(Math.max(1,10, -10,'1000')); //문자열이라도 숫자라면 자동형변환 해서 비교해줌
--결과값--
Infinity
-Infinity
-10
NaN
1000
console.log(Math.round(10.49));
console.log(Math.round(10.5));
console.log(Math.round(-10.5));
console.log(Math.round(-10.51));
--결과값--
10
11
-10
-11
console.log(Math.floor(10.49));
console.log(Math.floor(10.5));
console.log(Math.floor(-10.5));
console.log(Math.floor(-10.51));
--결과값--
10
10
-11
-11
console.log(Math.ceil(10.49));
console.log(Math.ceil(10.5));
console.log(Math.ceil(-10.5));
console.log(Math.ceil(-10.51));
--결과값--
11
11
-10
-10
const rn = Math.random();
console.log(rn);
const num = Math.floor(Math.random() * 10) + 1
console.log(num);
--결과값--
0.4888843985846216
3
String 객체
문자열을 손쉽게 다룰 수 있는 객체
const str1 = 'javascript';
const str2 = new String('javascript');
str1 == str2 // true
str1 === str2 // false
length: 문자열의 길이를 반환하는 프러퍼티
indexOf(): 특정 문자나 문자열이 처음으로 등장하는 위치를 리턴
charAt(): 특정 문자열에서 전달 받은 인덱스에 위치한 문자를 리턴
includes(): 특정 문자열에서 전달 받은 문자열이 포함되어 있는지 여부를 리턴
substring(): 전달 받은 시작 인덱스부터 종료 인덱스 바로 앞까지 문자열을 추출
substr(): 전달 받은 시작 인덱스부터 전달 받은 개수만틈 문자열을 추출
split(): 구분자를 기준으로 나눈 후 나뉜 문자열을 하나의 배열에 저장
replace(): 원본 문자열의 일부를 전달 받은 문자열로 치환
trim(): 문자열의 앞 뒤 공백을 제거
toUpperCase(): 모두 대문자로 변환
toLowerCase(): 모두 소문자로 변환
문자열의 길이를 반환
const str1 = '안녕하세요. JavaScript!';
console.log(str1);
console.log(str1.length);
--결과값--
안녕하세요. JavaScript!
18
특정 문자나 문자열이 처음으로 등장하는 위치를 리턴
console.log(str1.indexOf('J'));
console.log(str1.indexOf('Java'));
console.log(str1.indexOf('Java'));
console.log(str1.indexOf('a'));
console.log(str1.lastIndexOf('a'));
--결과값--
7
7
7
8
10
특정 문자열에서 전달 받은 인덱스에 위치한 문자를 리턴
console.log(str1.charAt(7));
특정 문자열에서 전달 받은 문자열이 포함되어 있는지 여부를 리턴
console.log(str1.includes('Java'));
console.log(str1.includes('java'));
--결과값--
J
true
false
전달 받은 시작 인덱스부터 종료 인덱스 바로 앞까지 문자열을 추출
console.log(str1.substring(7));
console.log(str1.substring(7,11));
--결과값--
JavaScript!
Java
console.log(str1.substr(7,4)); //4글자만 가져온다
자바랑 헷갈릴 수있으므로 자바스크립트만의 고유한 substring을 사용하자
--결과값--
Java
구분자를 기준으로 나눈 후 나뉜 문자열을 하나의 배열에 저장
const str2 = '김사과,오렌지,반하나,이메론,배애리,채리';
const students = str2.split(',');
for(let s in students){
console.log(s, students[s]);
}
--결과값--
[ '김사과', '오렌지', '반하나', '이메론', '배애리', '채리' ]
0 김사과
1 오렌지
2 반하나
3 이메론
4 배애리
5 채리
console.log(str1.replace('안녕하세요','hello'));
const str3 = ' JavaScript '; //앞뒤 공백만 제거
console.log(`❤${str3}❤`);
console.log(`❤${str3.trim()}❤`);
hello. JavaScript!
❤ JavaScript ❤
❤JavaScript❤
Date 객체
날짜, 시간등을 쉽게 처리할 수 있는 내장 객체
연도(year)
- 2자리로 연도를 표기: 1900년 ~ 1999년
- 4자리로 연도를 표기: 2000년 ~
월(month)
- 0(1월) ~ 11(12월)
Date 객체를 생성하는 방법
new Date(); 현재 날짜 시간을 저장한 객체가 생성
new Date('날짜 문자열'): 해당 특정 날짜와 시간을 저장한 객체가 생성
new Date('밀리초'): 1970년 1월 1일 0시 0분 0초 ~ 해당 밀리초만큼 지난 날짜와 시간을 저장한 객체가 생성
new Date(년, 월, 일, 시, 분, 초, 밀리초): 해당 특정 날짜와 시간을 저장한 객체가 생성
console.log(new Date());
console.log(new Date(22, 11, 7)); //년도를 2자리로 사용하면 1900년도
console.log(new Date(2022, 10, 7));
//console.log(new Date(2022, 10, 7,13,40,00));
const current_time = new Date(2022, 10, 7,13,40,00);
console.log(current_time.toString()); // 표준시로 출력
console.log(`현재 년도: ${current_time.getFullYear()}`);
console.log(`현재 월: ${current_time.getMonth()+1}`);
console.log(`현재 일: ${current_time.getDate()}`);
console.log(`현재 시간: ${current_time.getHours()}`);
console.log(`현재 분: ${current_time.getMinutes()}`);
console.log(`현재 초: ${current_time.getSeconds()}`);
--결과값--
2022-11-07T07:43:11.492Z
1922-12-06T15:00:00.000Z
2022-11-06T15:00:00.000Z
Mon Nov 07 2022 13:40:00 GMT+0900 (대한민국 표준시)
현재 년도: 2022
현재 월: 11
현재 일: 7
현재 시간: 13
현재 분: 40
현재 초: 0
console.log(new Date(1658000000000));//타임스탬프
--결과값--
2022-07-16T19:33:20.000Z
BOM(Browser Object Model): 비표준
웹 브라우저에 구현된 JavaScript 객체 모델을 의미하여 windwo 객체의 프로퍼티로 조회가 가능
window 객체
웹 브라우저의 창이나 탭을 표현하기 위한 객체들이며 웹 브라우저는 window 객체를 이요하여 브라우저 창을 표현할 수 있음
<!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>window 객체</title>
<style>
body{
background-color:rgb(60, 60, 60);
}
</style>
<script>
for(let wins in window){
console.log(`property: ${wins}, value: ${window[wins]}`);
}
</script>
</head>
<body>
<h2>window 객체</h2>
</body>
</html>
window객체의 property 매우 많음
안에 alert도 있고confirm 도 있고 prompt도있고 여러가지 기타등등
유용한 window 객체함수
setTimeout()
일정 시간이 지난 후 매개변수로 제공된 함수를 실행
const 함수명 = function(){
실행문;
...
}
const st = setTimeout(함수명, 시간);
clearTimeout()
setTimeout()를 취소함
<!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>setTimeout</title>
<script>
//const hello = console.log('hello') 이렇게 쓰면안되는이유는??
//바로 실행되기때문 function안에 넣으면 함수호출시에만 실행됨!
const hello = function(){
alert('안녕하세요. JavaScript!');
}
const st = window.setTimeout(hello, 2000) //2000 = 2second
//window 는 생략가능
//일정시간후에 실행해주는 함수를 콜백함수라함
//clearTimeout(st); //아예실행 안되게 해버림
</script>
</head>
<body>
</body>
</html>
2초 후
setInterval()
일정 시간마다 매개변수로 제공된 함수를 실행
clearInterval()
setInterval()를 취소함
<!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>setInterval</title>
<script>
const hello = function(){
console.log('안녕하세요. JavaScript!');
}
const si = setInterval(hello, 2000);
const clearInter = function(){
clearInterval(si);
console.log('hello() 중지되었음!');
}
</script>
</head>
<body>
<h2>setInterval</h2>
<p><button onclick="clearInter()">중지</button></p>
</body>
</html>
2초마다 입력
중지버튼 누르면 종료
<!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>clock</title>
<script>
let i = 1658000000000
const hello = function(){
i+=1000;
let current_time = new Date(i);
console.log(current_time);
}
let a=null;
const rep = function(){
a = setInterval(hello, 1000);
}
const clearInter = function(){
clearInterval(a);
console.log('hello() 중지되었음!');
}
</script>
<!-- <script>
강사님이 하신거
function printTime(){
const date = new Date();
const hh = date.getHours();
const mm = date.getMinutes();
const ss = date.getSeconds();
console.log(`${hh} : ${mm} : ${ss}`);
}
let timeId = null;
function startClock(){
timeId = setInterval(printTime, 1000);
}
function stopClock(){
clearInterval(timeId);
}
</script> -->
</head>
<body>
<p><button onclick="rep()">시작</button> <button onclick="clearInter()">종료</button></p>
</body>
</html>
시작누르면 시작, 종료누르면 정지, 다시 시작누르면 멈췄던 시간부터 다시 시작
location 객체
현재 브라우저에 표시된 HTML 문서의 주소를 얻거나, 브라우저에 새 문서를 불러올 때 사용
https://koreaisacademy.com/renewal2021/community/post.asp
------ ------------------- ------------------------------
protocol hostname pathname
protocol: 콜론을 포함하는 https, http, ftp등 프로토콜 정보를 리턴
hostname: 호스트의 이름과 포트번호를 리턴
pathname: URL 경로부분의 정보를 리턴
href: 페이지 URL 전체 정보를 리턴 or URL을 지정하여 페이지를 이동
<!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>location 객체</title>
<script>
console.log(`현재 문서의 URL 주소: ${location.href}`);
console.log(`현재 문서의 protocol: ${location.protocol}`);
console.log(`현재 문서의 hostname: ${location.hostname}`);
console.log(`현재 문서의 pathname: ${location.pathname}`);
// location.href = 'https://www.google.co.kr'; 페이지 실행하자마자 구글로 이동
function sendit(){
location.href = 'https://www.google.co.kr';
}
</script>
</head>
<body>
<h2>location 객체</h2>
<p><button onclick="sendit()">이동</button></p>
</body>
</html>
form 객체
일반적이 폼에 접근할 때 사용, document.forms 컬렉션을 이용해서 접근
<from name="myfrom" id="regform" method="post" action="regist.jsp">
아이디: <input type="text" name="userid" id="id"><br>
비밀번호: <input type="password" name="userpw" id="pw"></br>
</form>
폼 접근
const frm = document.myform; //document =body를 의미 (.)으로 접근하면 name으로 접근 이름이 myform인 것을 찾아줘
그럼 폼이 객체로 들어감
const frm = document.getElementById('regform');// id
const frm = document.forms['myform']; //name
const frm = document.forms[0]; 젤 위서 부터 첫번째인 폼을 갖고와라~
아이디 입력상자 접근(폼을 찾았다는 전제하에)
const userid = frm.userid; //name
const userid = document.getElementById('id');
const userid = documnet.forms['myform'].elements[0];
const userid = documnet.forms['myform'].elements['userid]];
const userid = document.forms[0][0];
<!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>form 객체</title>
</head>
<body>
<h2>form 객체</h2>
<form action="#" name="frm1">
<input type="text" name="userid" id="id" placeholder="아이디 입력"><br>
<input type="password" name="userpw" placeholder="비밀번호 입력">
</form>
<form action="#" name="frm2">
<input type="search" name="search" placeholder="검색어 입력"><br>
</form>
</form>
<script>
const frm1 = document.frm1;
console.log(frm1.userid.placeholder);
const frm2 = document.frm2;
console.log(frm2.search.placeholder);
document.getElementById('id').value = 'apple';
document.forms['frm1'].elements['userpw'].value = '1004';
document.forms[1].elements[0].value='코랴it아카데미'
</script>
</body>
</html>
'웹 개발 > 🌐 JavaScript' 카테고리의 다른 글
JavaScript | 함수,오브젝트,클래스,상속,래퍼객체 (0) | 2022.11.09 |
---|---|
JavaScript | history,navigator,dom,node,정규표현식 (1) | 2022.11.08 |
호이스팅, var, let (0) | 2022.11.07 |
JavaScript | 대화상자,제어문,반복문,배열,호이스팅 (0) | 2022.11.07 |
JavaScript | 출력,변수,상수,데이터 타입,타입변환 (0) | 2022.11.06 |