Develop/Node.js

[기초]02. 자바스크립트의 기초

dawonny 2022. 1. 31. 03:13
728x90
반응형

배웠지만 다시 기초 복습한다치고 정리해보자


기본 문법

 

세미콜론 ; 으로 문장 종료

{ } 이용해서 구역나눔.

조건문. 반복문 있음

var a = 1; 
b = 2;
// 2
console.log("a:" + a);
console.log("b:" + b);

var c = 3, d = 10;
var str1 = "Hello";
var str2 = "World!";
var str3 = null;

console.log("c:" + c);
console.log("d:" + d);
console.log(str1);
console.log(str2);
console.log(str3);

//결과
a:1
b:2
c:3
d:10
Hello
World!
null

 

연산자

 

산술연산자에는 + - * / 

++ -- 가 있다

var a = 1;
var b = 2;
var c = 3, d = 10;

a = b + 1;
//3

a = b - 1;
//1

a = b * d;
// 20

a = a / 10;
// 2

a++;
// 2

a;
// 3

a--;
// 3

a;
// 2

 

데이터 타입

 

js 는 별도의 자료형을 명시하진 않는다. 입력되는 값에 의해 자료형이 판별되니까!

변수가 객체를 선언할 때에는 var 키워드를 사용함.

js 의 기본 자료형인 number, string, boolean 은 기본으로 내장.

 

Number

 

10, 8, 16진수, 소수점이 있는 실수 및 지수 사용가능

var int_data = 1;
var float_data1 = Number('1.0');
var float_data2 = new Number('4.1254'); 
typeof int_data
// "number"

typeof float_data1;
// "number"

typeof float_data2;
// "object"

console.log((255).toString(10));
// "255"

console.log((255).toString(16));
// "ff"

console.log((255).toString(8));
// "377"

console.log((255).toString(2));
// "11111111"

 

String

 

 문자열 값을 가지는 자료형이다.

var character1 = 'a';
var character2 = "b";
var string1 = "Double Quotations";
var string2 = 'Single Quotation Anyway'; 
var string3 = new String("String Object"); 

typeof string1;
// "string"

typeof string3;
// "object"

string2[4];
// "l"

console.log(string2.charAt(4));
// "l"
console.log(string3[1]);
//"t"

console.log(string1.length);
// 17

console.log(string1.toUpperCase());
// "DOUBLE QUOTATIONS"

console.log(string2.toLowerCase());
// "single quotation anyway"

console.log(string3.indexOf('g'));
// 5
console.log(string3.indexOf('x'));
// -1

Boolean

 

true 나 false 값을 가짐

var result1 = new Boolean();
var result2 = true;

typeof result1;
// "object"
typeof result1.valueOf();
// "boolean"

console.log(Boolean("test"));
// true
console.log(Boolean(""));
// false
console.log(Boolean({}));
// true

Array

var array1 = [1, 2, 3];
var array2 = new Array(1, 2);
array2.push(3);
// 3
var array3 = new Array(3); 
array3;
// [undefined × 3]

typeof array1;
// "object"

array1.toString();
// "1,2,3"

array1.valueOf();
// [1, 2, 3]

array1.length;
// 3

array1[1];
// 2

array1.length = 5;
// 5

array1;
// [1, 2, 3, undefined × 2]

console.log(array2.push("new1"));
// 4

console.log(array2.push("new2"));
// 5

array2;
// [1, 2, 3, "new1", "new2"]

array2.pop();
// "new2"
console.log(array2);
// [1, 2, 3, "new1"]

array3 = new Array(4, 2, 1, 3, 0);
// [4, 2, 1, 3, 0]

console.log(array3.sort());
// [0, 1, 2, 3, 4]

조건문 

var a = 3;
var result = '';
if(a > 2){
	result = 'a is greater than 2';
}
else if(a == 2){
	result = 'a is 2';
}
else{
	result = 'a is smaller than 2'; 
}

console.log(result);
// "a is greater than 2"

switch 를 이용한 조건문

var a = 1; 
var result = '';
      
switch (a) {
	case 1:
		result = 'Number 1';
  break;
	case 2:
		result = 'Number 2';
    break;
	default:
		result = 'I do not know what number';
break; 
}

console.log(result);
// "Number 1"

 


조건문 실습 - 양수 구별하기

if else 구문 활용해서 입력한 정수가 음수인지 양수인지 판별

// Run by Node.js

const readline = require("readline");
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

rl.on("line", function(line) {
	// if문 이용
	// 입력받은 값을 같이 출력하고 싶다면 아래와 같이 사용
	// 입력 값은 line에 들어가 있음
	if(line>1){
		console.log("양수");
	}
	else if(line==0){
		console.log("0");
	}
	else{
		console.log("음수");
	}
	rl.close();
}).on("close", function() {
	process.exit();
});

조건문 실습 - 자판기

switch 문을 이용해서 음료수 이름 출력하는 프로그램 만들기

// Run by Node.js

const readline = require("readline");
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

rl.on("line", function(line) {
	// if문과 switch문 이용
	// 입력값 출력은 아래와 같이 사용
	// console.log(line);
	
	switch(line){
			case '300':
				console.log("코코팜");
				break;
		case '200':
			console.log("웰치스");
			break;
		case '500':
			console.log("아이스티");
			break;
		default:
			console.log(line);
			break;
	}
	rl.close();
}).on("close", function() {
	process.exit();
});

반복문 - for

var array = new Array();

for (var i = 0; i < 10; i++) {
	array.push(i);
}

console.log(array.toString());
// "0,1,2,3,4,5,6,7,8,9"

js에는 for 문의 다른 형태로 for-in 문이 있다.

var a = ['a', 'b', 'c', 'x', 'y', 'z'];
var result = '';

for (var i in a) {
	result += 'index:'+ i + ', value:'+ a[i] + '\n'; 
}

console.log(result);

// "index:0, value:a
// index:1, value:b
// index:2, value:c
// index:3, value:x
// index:4, value:y
// index:5, value:z"

반복문 - while, do while

var i = 0;

while (i < 10) {
	i++; 
}

console.log(i);
// 10

do-while 은 do 구문 뒤에 바로 코드 블록이 오고 그다음에 조건문이 온다

그래서 조건문이 거짓이더라도 최소 한번은 do 블록이 실행됨

var i = 0; 

do {
  i++;
} while (i < 10)
  
console.log(i)
// 10

반복문 실습 - 역순으로 출력하기

// Run by Node.js
// 출력은 console.log 이용하기
var i = 10;

while(i>0){
	console.log(i);
	i--;
}

함수

 

함수를 선언할 때에는 function 이라는 키워드를 사용

함수의 반환값에 대한 자료형은 명시 안해도됨.

 

함수는 하나의 데이터로서 취급된다.

function sum(a, b) { 
	var c = a + b;
	return c; 
}

console.log(sum(1, 2));
// 3

delete 키워드를 사용하면 메모리 공간에 할당된 객체의 속성을 삭제할 수 있다.

delete 연산이 성공하거나 / 존재하지 않는 속성이라 아무런 연산을 못한경우 - true 출력

실패할 경우 - false 출력

function sum(a, b) { 
	var c = a + b;
	return c; 
}

var add = sum;
typeof add;
//"function"

add(1,2);
// 3

var student = {
	name : 'goorm',
	age : 20
}

console.log(student.name);

delete student.name;
// true

console.log(student.name);
//undefined

delete student;
// false

delete not_exist;
// true

console.log(student.age);

익명함수(Anonymous Function)

한 번 쓰고 버릴 함수의 경우 익명함수로 사용

보통 함수 표현식, 콜백함수, 즉시실행함수의 경우에서 많이 사용

var f = function (a) {
  return "This is anonymous function!"; 
};

console.log(f());

// "This is anonymous function!"

콜백 함수(Callback Function)

특정 이벤트가 발생하면 호출되는 함수

(ex : 버튼을 클릭, 네트워크를 통해 어떤 데이터 도착)

function one() {
  return 1;
}

var two = function () {
  return 2;
}
function invoke_and_add(a, b) {
  return a() + b();
}

console.log(invoke_and_add(one, two));
// 3

위 소스 코드를 보면 one 과 two 함수 자체가 한 함수의 인자로서 전달됨

function one() { 
	return 1;
}
function invoke_and_add(a, b) {
  return a() + b();
}
invoke_and_add(one, function() { 
  return 2; 
});

//3

위 소스코드에서는 조금 다르게 인자로 넣어주는 동시에 익명함수를 생성했다.


함수 실습 - 제곱 값 출력하기

// Run by Node.js

const readline = require("readline");
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
});

var f = function(a){
	return a*a;
};

rl.on("line", function(line) {
	console.log(f(line));
	rl.close();
}).on("close", function() {
	process.exit();
});

 

728x90
반응형