console.log('A');
console.log('B');
var i = 0;
while(i < 2){
console.log('C1');
console.log('C2');
i = i + 1;
}
console.log('D');
/*결과값: A B C1 C2 C1 C2 D*/
배열 자료형
var arr = ['A','B','C','D'];
console.log(arr[1]);
console.log(arr[3]);
arr[2] = 3;
console.log(arr);
console.log(arr.length);
arr.push('E');
console.log(arr);
/*결과값 B D [A, B, 3, D] 4 [A, B, 3, D, E]*/
- arr.length :: 배열의 길이
- arr.push() :: 배열 삽입
+) 배열 & 반복문
var number = [1,400,12,34];
var i = 0;
var total = 0;
while(i < number.length){
total = total + number[i];
i = i + 1;
}
console.log(`total : ${total}`);
/*total : 447*/
함수
function f123(){
console.log(1);
console.log(2);
console.log(3);
console.log(4);
}
ㄴ 다른 컴퓨터 언어와 똑같이 JavaScript에서도 함수의 return 값을 전달하도록 할 수 있다.
Node.js
현재 디렉토리에서 파일 목록 알아내기
var testFolder = './data'; // './' <- 는 현재 디렉토리! 라는 뜻. 생략해도 되지만 쓰는게 더 명확
var fs = require('fs');
fs.readdir(testFolder, function(error, filelist){
console.log(filelist); //배열로 출력, readdir:는 파일목록을 배열로 처리한다.
})
fs.readdir 는 파일 목록을 배열로 처리해주는 명령어이다.
이걸 이용하면 main 파일의 로직 변경 없이 파일을 자유롭게 추가하고, 수정할 수 있게 된다. 이렇게 되면 훨씬 간편할 뿐만 아니라 변경점이 있을 때마다 서버를 끄고 켤 필요가 없어진다.
fs.readdir('./data', function(error, filelist){
var title = 'Welcome';
var description = 'Hello, Node.js';
var list = '<ul>';
var i = 0;
while(i < filelist.length){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i = i + 1;
}
list = list+'</ul>';
var template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.writeHead(200);
response.end(template);
})
함수를 이용해서 이제까지 계속 작성해오던 코드에서 중복인 부분을 생략하고, 훨씬 융통성 있게 정리할 수 있다.
정의한 함수
function templateHTML(title, list, body){
return `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${body}
</body>
</html>
`;
}
function templateList(filelist){
var list = '<ul>';
var i = 0;
while(i < filelist.length){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i = i + 1;
}
list = list+'</ul>';
return list;
}
함수 활용
var list = templateList(filelist);
var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
response.writeHead(200);
response.end(template);