문법
let str1='10';
let str2='20';
console.log('두 문자 더하기=%s',str1+str2); //두 문자 더하기=1020
let num1=10;
let num2=20;
console.log('두 숫자 더하기=%d',num1+num2); //두 숫자 더하기=30
- isNaN
const isNum=isNaN(20); //is Not a Number
const isNum2=isNaN(-20);
const isNum3=isNaN('50'); //따옴표 속에 있는 숫자로 인식됨
const isNum4=isNaN('hello');
console.log(isNum); //false //=is a number
console.log(isNum2); //false
console.log(isNum3); //false
console.log(isNum4); //true
- 문자열
const str='computer';
console.log('문자열길이 :',str.length); //문자열길이 : 8
console.log(str+'라는 문자에서 마지막 글자는 %s입니다',str[7]);
console.log(`${str}라는 문자에서 마지막 글자는 ${str[str.length-1]}입니다`);
//computer라는 문자에서 마지막 글자는 r입니다
console.log(str.indexOf('com')); //0 (글자 시작 위치)
console.log(str.indexOf('put')); //3
console.log(str.indexOf('the')); //-1 //없음
- 배열
const num1=[10,20,30];
const num2=new Array(10,20,30);
const str1=['김철수','이영희'];
const str2=new Array('김철수','이영희');
const str3=[];
num3.push(10);
num3.push(20);
num3.push(30);
console.log(str1[0]) //김철수
console.log(str2); //[ '김철수', '이영희' ]
- 타입
const pi=3.14;
console.log('pi변수의 타입=',typeof pi); //pi변수의 타입= number
console.log('hello 문자 타입= %s',typeof 'hello'); //hello 문자 타입= string
console.log('[] 객체타입= %s',typeof []); //배열객체 //[] 객체타입= object
console.log('{} 객체타입= %s',typeof {}); //제이슨객체 //{} 객체타입= object
console.log('true의 타입 %s',typeof true); //true의 타입 boolean
console.log(typeof 10>20); //false
const num=!1; //1=true
console.log(num); //false
- 삼항연산자
let num1=20;
let num2=40;
let max=num1>num2?num1:num2;
console.log(`두 수 중 큰 값은 ${max}입니다`); //두 수 중 큰 값은 40입니다
const arr1=[10,20,30];
const arr2=[];
arr1.length>0?console.log(arr1):console.log('배열 빔'); //[10,20,30]
arr2.length>0?console.log(arr2):console.log('배열 빔'); //배열 빔
- date
const today=new Date();
const date1=new Date(2022,12-1,24); //month는 0~11 기준
const date2=new Date(2022,12-1,25, 18, 30, 20);
console.log(today.toLocaleString());
console.log(date1.toLocaleString());
console.log(date2.toLocaleString());
console.log('날짜 : %s',today.toLocaleDateString());
console.log('시간 : %s',today.toLocaleTimeString());
console.log('년도 : %s',today.getFullYear());
console.log('월 : %s',today.getMonth()+1);
console.log('일 : %s',today.getDate());
//금액
let price=79747748;
console.log(price.toLocaleString()+'원');
- 오늘 날짜 원하는 형식으로 출력
function getDate(date){
const y=date.getFullYear();
const m=date.getMonth()<9?`0${date.getMonth()+1}`:date.getMonth()+1;
//1~9월이면 a / 10월부터 b
const d=date.getDate()<10?`0${date.getDate()}`:date.getDate();
return `${y}-${m}-${d}`;
}
const date1=getDate(new Date());
console.log('오늘 날짜 :',date1);
- 타임스탬프 : 날짜와 시간을 숫자로 표현해놓은 값
const date=new Date();
const today=new Date(1660044154580);
const dateToTimestamp=date.getTime();
const timestampToinit=new Date(1);
console.log('오늘 날짜의 타임스탬프 :',dateToTimestamp);
console.log('타임스탬프 초기 날짜 :',timestampToinit);
console.log('오늘 날짜 :',today.toLocaleString());
//
오늘 날짜의 타임스탬프 : 1660044154580
타임스탬프 초기 날짜 : 1970-01-01T00:00:00.001Z
오늘 날짜 : 2022. 8. 9. 오후 8:22:34
- 문제 : 100일 후 날짜 출력
function getDate(date){
const newDate=new Date(date);
const y=newDate.getFullYear();
const m=newDate.getMonth()<9?`0${newDate.getMonth()+1}`:newDate.getMonth()+1;
const d=newDate.getDate()<10?`0${newDate.getDate()}`:newDate.getDate();
return `${y}-${m}-${d}`;
}
//100일 계산
let day=100;
const date=new Date();
const dateTimestamp=date.getTime();
let dday=getDate(dateTimestamp+(day*24*60*60*1000));
console.log('%d일 기념일=>%s',day,dday);
//
오늘 날짜 : 2022-08-09
100일 기념일=>2022-11-17
for문
- 문제 : 배열에 있는 학생 성적 출력, 배열에 없으면 명단에 없음 알림
const studentList=[
{name:'김철수',kor:80,eng:70,mat:87},
{name:'이영희',kor:100,eng:98,mat:90},
{name:'홍길동',kor:90,eng:56,mat:70}
];
let searchName='이영희';
let i;
for (i=0;i<studentList.length;i++){
if (studentList[i].name==searchName){
break;
}
}
if (i==studentList.length){ //위 for문 괄호 속에서 i++ 한 후, 조건에 맞지 않아 빠져나오게 됨 (i=4)
console.log('시험명단에 없습니다');
}else{
console.log(`${studentList[i].name}의 성적 \n국어 ${studentList[i].kor}\n영어 ${studentList[i].eng}\n수학 ${studentList[i].mat}`);
}
- for of 문
for (const [key, value] of array.entries()) {
console.log(key, value)
}
키에만, 키&값에 접근 가능
await, break, continue 사용 가능
let fruits=['사과','복숭아','바나나'];
for(const choice of fruits){ //배열값 하나씩 전달
console.log('과일=>',choice);
}
//
과일=> 사과
과일=> 복숭아
과일=> 바나나
- 문제
let searchName='이영희';
let findName;
for(const student of studentList){
if(student.name==searchName){
findName=student;
}
}
if (findName==undefined){
console.log('명단에 없습니다');
} else{
console.log(`${findName.name}의 성적표`);
console.log('국어 =>',findName.kor);
console.log('영어 =>',findName.eng);
console.log('수학 =>',findName.mat);
}
- forEach문
array.forEach((e, index) => {
console.log(e, index)
})
배열값, 인덱스에 모두 접근 가능
중간에 루프 탈출 불가
const studentList=[
{name:'김철수',kor:80,eng:70,mat:87},
{name:'이영희',kor:100,eng:98,mat:90},
{name:'홍길동',kor:90,eng:56,mat:70}
];
studentList.forEach((student)=>{
console.log(student)
});
//
{ name: '김철수', kor: 80, eng: 70, mat: 87 }
{ name: '이영희', kor: 100, eng: 98, mat: 90 }
{ name: '홍길동', kor: 90, eng: 56, mat: 70 }
- 문제 : 점수합 구하기
const scores=[85,96,74,63,90];
let sum=0;
scores.forEach((score)=>{
sum+=score;
});
console.log(sum);
JSON (Javascript Object Notation) : 자바스크립트 객체 표기법
const person = {};
person.name='홍길동';
person.job='도적';
console.log(person); //{ name: '홍길동', job: '도적' }
console.log(person.name); //홍길동
const product={
name:'망고통조림',
price:3000,
origin:'필리핀'
}
console.log(product.price); //3000
console.log(product['name']); //망고통조림
const na='name';
console.log(product[na]); //망고통조림 //na 변수값인 name 가져옴
- JSON 형식으로 파일에 저장하기
const fs=require('fs'); //fs: 컴퓨터 파일 시스템에 접근 -> 특정 디렉터리(폴더)나 파일을 읽고 쓰는 기능 위한 모듈
const userList=[
{name:'홍길동',age:50,address:'서울시 종로구'},
{name:'김철수',age:35,address:'서울시 중구'},
{name:'이영희',age:22,address:'서울시 서초구'}
];
fs.writeFile('./list.json',JSON.stringify(userList),()=>{ //stringify: js->json 파싱
//저장 명령(생성할 파일, 작성할 내용, 콜백)
console.log('저장완료');
});
=> list.json 파일 저장됨
[{"name":"홍길동","age":50,"address":"서울시 종로구"},{"name":"김철수","age":35,"address":"서울시 중구"},{"name":"이영희","age":22,"address":"서울시 서초구"}]
- JSON 파일 불러오기
const fs=require('fs');
fs.readFile('./list.json',(err,data)=>{ //파일 읽기(파일 위치,함수(에러,읽을내용))
if(err){
console.log('파일을 읽을 수 없습니다');
}else{
const json=JSON.parse(data.toString()); //JSON->JS 파싱해 변수에 저장
for(let i=0;i<json.length;i++){
console.log(`이름 : ${json[i].name} 나이 : ${json[i].age}`);
}
}
});
//
이름 : 홍길동 나이 : 50
이름 : 김철수 나이 : 35
이름 : 이영희 나이 : 22
참고:
https://moonheekim-code.tistory.com/108
[node js] Express: Model 에서 file형태로 데이터 저장 및 읽어오기
기존에 MVC 패턴 구현에서 한걸음 더 나아가, Model 에서 클라이언트로부터 받아온 파라미터를 array로 저장하지 않고 file로 저장해보도록 한다. models / product.js 파일 ( product 관련 데이터를 다루는
moonheekim-code.tistory.com
'Programming > 국비학원' 카테고리의 다른 글
220811 - 자바스크립트 - 함수, 배열, 클로저 (0) | 2022.08.12 |
---|---|
220810 - 자바스크립트 - 문법 (0) | 2022.08.11 |
220808 - 리액트 - redux, es6 (0) | 2022.08.09 |
220805 - 리액트 - 생명주기, AJAX (0) | 2022.08.06 |
220804 - 리액트 - 라우터돔 (0) | 2022.08.05 |