IT보안따라잡기

JavaScript 기초 문법 본문

프로그래밍/자바스크립트

JavaScript 기초 문법

보안바라기 2021. 5. 31. 16:59
반응형

1. 변수

자바스크립트에는 변수형(int, double, string)이 존재하지 않으며, var라는 가변형 변수만 존재하여 초기화할 때 형태에 따라서 알아서 할당된다.

var i;

var x = 1234;

var y = "1234";

var z = true;

var w = null;

 

- var의 유효 범위는 함수 내부로 조건문이나 반복문 안에서 초기화된 경우라도 함수 내부 블록이라면 어디서나 호출할 수 있음.

- 최신 자바스크립트에선 let이라는 블록 지역 변수를 제공하고 있음.

 

2. 연산자

+,-,*,/,% 등의 기본 연산은 물론 ++,--와 같은 증감 연산자도 사용이 가능하다.

a = a + 1 (x)

a += 1 (o)

 

- 자바스크립트에서는 위와 같은 표현은 쓰지 말라고 기재되어 있으며, 무조건 할당 연산자를 사용하라고 함.

- 자바와 마찬가지로 string concatenation 되므로 문자열을 덧셈기호로 간단히 붙일 수 있음.

 

* string concatenation이란?

- 왼쪽에서 오른쪽으로 진행되며, 문자열 덧셈은 모든 것을 문자열로 만드는 것.

var s = "test1" + "test2";

document.write(s);

test1test2

 

3. 조건문

a==b

a!=b

a==b && a==c

a==b || a==c

a > b

 

var a=1;

var b=1;

document.write(a==b);

true

 

var a=1;

var b=2;

document.write(a==b);

false

 

var a=1;

var b=0;

if(a>b) {

document.write("a is more then b.")

} else if(a==b){

document.write("a is the same as b.")

} else {

document.write("a is less than b")

}

a is more then b.

 

4. 함수

선언과 호출은 아래와 같이 작성한다.

function send() {

alert('send');

}

send();

 

자바스크립트의 함수는 굉장히 다채롭게 선언할 수 있으며, 아래와 같이 함수를 생성할 수도 있다.

send = function() {

alert('send');

}

send();

 

최근 자바스크립트 문법에선 화살표 함수라는 개념으로 도입되어 아래와 같이 생성할 수도 있다.

send = () => {

alert('send');

}

send();

 

위처럼 여러 가지 형식을 가지고 있는데, 정해진 규칙은 없으므로 자신이 원하는 방식으로 일관성 있게 작성하면 된다.

다만 화살표 함수의 경우엔 구형 브라우저에선 인식되지 않을 수 있다.

 

값을 반환하는 함수는 아래와 같이 작성

function add(value1, value2) {

return value1 + value2;

}

 

var a = 10;

var b = 20;

var sum = add(a, b);

document.write(sum);

30

 

5. 배열

변수의 값이 연속적으로 나열된 형식

 

배열의 선언

var arr= new Array;

var arr = [];

 

배열에 값 삽입

var job = [];

job[0] = "Warrior";

job[1] = "Archer";

job[2] = "Wizard";

var job = ["Warrior", "Archer", "Wizard"];

 

배열과 관련된 메서드

var job = ["Warrior", "Archer", "Wizard"];

document.write("Total Jobs : " + job.length);

Total Jobs : 3

 

자바스크립트에서 length라는 속성을 통해 문자열의 길이를 구할 수 있다.

length 속성은 문자열에서 문자의 개수를 return 해준다.

공백의 경우에도 한 개의 문자로 인식하여 length에 포함시켜준다.

 

var job = ["Warrior", "Archer", "Wizard"];

document.write("Total Jobs : " + job.join(","));

Total Jobs : Warrior,Archer,Wizard

 

var job = ["Warrior", "Archer", "Wizard"];

document.write("Total Jobs : " + job.reverse());

Total Jobs : Wizard,Archer,Warrior

 

var job = ["Warrior", "Archer", "Wizard"];

document.write("Total Jobs : " + job.sort());

Total Jobs : Archer,Warrior,Wizard

 

var job = ["Warrior", "Archer", "Wizard"];

var DLC_job = ["Assasin", "Samurai"];

document.write("Total Jobs : " + job.concat(DLC_job));

Total Jobs : Warrior,Archer,Wizard,Assasin,Samurai

 

var job = ["Warrior", "Archer", "Wizard"];

document.write("<p>" + "Total Jobs : " + job.push("Devil", "Outlaw" + "</p>"));

document.write("<p>" + "Total Jobs : " + job.pop( + "</p>"));

document.write("<p>" + "Total Jobs : " + job.pop( + "</p>"));

document.write("<p>" + "Total Jobs : " + job);

Total Jobs : 5

Total Jobs : Outlaw

Total Jobs : Devil

Total Jobs : Warrior,Archer,Wizard

 

push와 pop은 자료구조 Stack에서 다뤄지며 javascript에도 동일한 기능을 수행한다.

push는 맨 뒤에 요소를 삽입 pop은 맨 뒤에 요소를 꺼내는 것이다.

 

6. 오브젝트(Object)

구조체(struct)처럼 내부에 여러 변수를 가질 수 있고 클래스(class)처럼 내부에 메서드를 포함하고 있는 형식이다.

JSON이라고 많이 알려진 형식이다.

 

오브젝트의 선언

var obj = new Object;

var obj = {};

 

변수를 가진 오브젝트

hp와 mp를 가진 player를 생성해보자.

var player = {};

player.hp = 100;

player.mp = 300;

var player = {

hp: 100,

mp: 300

};

 

메서드를 가진 오브젝트

플레이어가 공격당하는 기능을 넣어보자

var player = {

hp: 100,

mp: 300,

hit: function() {

this.hp -= 10;

document.write("HIT!!");

}

};

player.hit();

document.write("<p>" + "player hp : " + player.hp);

HIT!!

player hp : 90

 

오브젝트 할당

위는 플레이어가 선언됨과 동시에 사용되고 있다.

만일 클래스 혹은 구조체처럼 단지 구조만 선언하고 싶은 경우에는 어떻게 표현할 수 있을까?

오브젝트를 함수로 선언하면 된다.

 

var Player = function(name) {

var name = name;

var hp = 100;

var mp = 300;

return {

hit: function(damage) {

hp -= damage;

document.write("HIT!!");

},

die: function() {

return hp == 0 ? true : false;

}

}

}

var medic = new Player('medic');

medic.hit(50); // HIT!!

document.write(medic.die()); // false

var fireBet = new Player('fireBet');

fireBet.hit(100); // HIT!!

document.write(fireBet.die()); // true

 

위와 같은 방법이 클로져라는 개념을 응용한 방식인데, 다음과 같이 선언하여 하나의 구조체를 여러 변수에서 할당받아 사용할 수 있다.

 

* 클로저(Closure)

- 클로저(closure)는 내부 함수가 외부 함수의 맥락(context)에 접근할 수 있는 것을 가리킨다.

- 외부 함수의 지역변수를 사용하는 내부 함수가 소멸될 때까지 소멸되지 않는 특성을 의미한다.

- 자신의 생성된 시점의 환경을 기억하는 함수

- 자바스크립트를 이용한 고난도의 테크닉을 구사하는데 필수적인 개념으로 활용한다.

 

7. 반복문

반복문이 나오는 이유는 반복적인 작업을 더욱 효율적으로 응용할 수 있기 때문이다.

아래는 가장 기본적으로 사용되는 방식의 반복문이다.

for(var i=0; i<5; i++) {
    document.write(i);
}
var i = 0;
while(i<5) {
    document.write(i);
    i++;
}

01234

 

FOR (변수 in 객체 또는 배열)

var arr = [10, 20, 30, 40, 50];

for(var i in arr) {
    document.write(i);
}

01234

 

in의 경우에는 배열이나 객체의 개수의 인덱스가 i에 할당되어 반복이 진행된다.

 

FOR (변수 of 객체 또는 배열)

var arr = [10, 20, 30, 40, 50];

for(var i of arr) {
    document.write(i);
}

1020304050

 

of의 경우에는 배열이나 객체의 값이 i에 할당되어 반복이 진행된다.

혹은 forEach나 map을 이용해서 객체의 반복을 실행할 수 있다.

var arr = [10, 20, 30, 40, 50];

arr.forEach((value) => {
    document.write(value);
});

arr.map((value) => {
    document.write(value);
});

해당 코드 모두 동일하게 아래의 결과를 출력한다.

1020304050

 

속도는 forEach가 빠르다고 알려져 있지만, map은 함수형 프로그래밍에 사용되는 개념으로 forEach와 다르게 새로운 객체를 반환하며, map에선 값과 동시에 인덱스를 출력할 수도 있다.

arr = [10, 20, 30, 40, 50];

arr.map((value, index) => {
    // value = 10, index = 0
    // value = 20, index = 1
    // value = 30, index = 2
    // value = 40, index = 3
    // value = 50, index = 4
});
document.write(arr);

10,20,30,40,50

 

8. 문자열(String)

문자열은 가장 기본적인 구조이며, 다양한 함수들이 존재하여 알아두어야 할 기능들이 많다.

var Welcome = "ONDE Planet is the most peaceful space in the universe";

document.write(Welcome.charAt(0));
// charAt(n) : n번째 문자를 출력한다. 결과는 O

document.write(Welcome.charCodeAt(0));
// charCodeAt(n) : n번째 문자의 유니코드를 출력한다. 결과는 79

document.write(Welcome.indexOf("x"));
// indexOf("?") : ?라는 글자가 있다면 글자의 인덱스를, 없다면 false(-1)을 출력한다. 결과는 -1

document.write(Welcome.includes("space"));
// includes("?") : ?라는 글자가 있다면 true(0), 없다면 false(-1)을 출력한다. 결과는 0

document.write(Welcome.replace("peaceful", "nasty"));
// replace("a", "b") : a를 b로 교체한다. 결과는 ONDE Planet is the most nasty space in the universe.

document.write(Welcome.search("universe"));
// search("?") : ?라는 글자를 검색하여 첫 문자의 시작 지점을 알려준다. 결과는 46

document.write(Welcome.slice(0,4));
// slice(n, n') : n~n'-1 까지의 문자를 가져온다. 결과는 ONDE

document.write(Welcome.split(" "));
// split("?") : ?라는 문자를 기준으로 문자열을 분리한다. 결과는 ONDE,Planet,is,the,most,peaceful...

document.write(Welcome.trim());
// trim() : 앞, 뒤의 공백을 제거하는 역할을 한다. 이 값에서는 앞뒤에 공백이 없으므로 결과가 본래의 문자열과 동일하다.

document.write(Welcome.length);
// length : 문자열의 길이를 반환한다. 결과는 55

 

concat() - 문자열 합치기

형식 : str.concat(string2, string3[, ..., stringN])
매개 변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환한다.
기존 문자열을 변경시키지 않는다.

let str1 = 'Hello,';
let str2 = 'world!';

document.write(str1.concat(str2)); // Hello,world!
document.write(str1); // Hello,
document.write(str2); // world!

Hello,world!Hello,world!

 

includes() - 문자열에 특정 문자열 포함 여부 확인

형식 : str.includes(searchString[, position])
position : 이 문자열에서 검색을 시작할 위치. 기본값은 0.

let sentence = 'Hello. My name is Jessie';

document.write(sentence.includes('Jessie')); // true
document.write(sentence.includes('Hello', 10)); // false

truefalse

 

split() - 배열로 만들기

형식 : str.split([separator[, limit]])
문자열을 지정된 구분자로 나눈 후 배열로 반환한다.
limit : 배열의 원소를 limit 개까지 처리한다.
기존 문자열을 변형시키지 않는다.

let str = '프론트엔드 개발을 해봐요.';

document.write(str.split(' ')); // ["프론트엔드", "개발을", "해봐요."]
document.write(str.split(' ', 2)); // ["프론트엔드", "개발을"]
document.write(str); // "프론트엔드 개발을 해봐요."

프론트엔드,개발을,해봐요.프론트엔드,개발을프론트엔드 개발을 해봐요.

 

replace() - 특정 문자열 교체하기

형식 : str.replace(regexp|substr, newSubstr|function)
어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환한다.
기존 문자열을 변형시키지 않는다.

let str = 'HELLO, My name is Jessie.';

// 최초 등장하는 패턴 한 번만 찾음
document.write(str.replace('e', '_')); // HELLO, My nam_ is Jessie.

// 모든 패턴 찾음
document.write(str.replace(/e/g, '_')); // HELLO, My nam_ is J_ssi_.

// 대소문자 구분 없이 모든 패턴 찾음
document.write(str.replace(/e/gi, '_')); // H_LLO, My nam_ is J_ssi_.

// 기존 문자열은 변형시키지 않음
document.write(str); // HELLO, My name is Jessie.

HELLO, My nam_ is Jessie.HELLO, My nam_ is J_ssi_.H_LLO, My nam_ is J_ssi_.HELLO, My name is Jessie.

 

slice() - 문자열 일부분으로 새로운 문자열 구하기

형식 : str.slice(beginIndex[, endIndex])
문자열의 beginIndex부터 endIndex - 1까지의 문자열을 추출하여 새로운 문자열을 반환한다.
Index 값이 음수라면, strLength(문자열 길이) + Index값으로 처리한다
기존 문자열을 변형시키지 않는다.

let str = 'I am Frontend Developer!';

document.write(str.slice(5, 13)); // Frontend
document.write(str.slice(5)); // Frontend Developer!
document.write(str.slice(5, -3)); // Frontend Develop
document.write(str.slice(-5)); // oper!

FrontendFrontend Developer!Frontend Developoper!

 

indexOf() - 주어진 문자열과 첫 번째로 만나는 문자열의 인덱스 구하기

형식 : str.indexOf(searchValue[, fromIndex])
fromIndex : 문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값
존재하지 않을 경우 -1 을 반환한다.

let str = 'I love JavaScript and TypeScript';

document.write(str.indexOf('Script')); // 11
document.write(str.indexOf('Script', 20)); // 26
document.write(str.indexOf('Script', 30)); // -1

1126-1

 

match() - 문자열에서 정규식과 매치되는 모든 부분을 검색하여 배열로 만들기

형식 : str.match(regexp)

let str = 'I love JAVASCRIPT and TypeScript';
let pattern = /script/gi; // 전역에서 대소문자 구별하지 않고 찾겠다는 뜻

document.write(str.match(pattern)); // ["SCRIPT", "Script"]

SCRIPT,Script

 

toUpperCase() / toLowerCase() - 각각 대문자/소문자로 변환하기

형식 : str.toUpperCase(), str.toLowerCase()

기존 문자열을 변형시키지 않는다.

let str = 'AbCdEfG';

document.write(str.toUpperCase()); // ABCDEFG
document.write(str.toLowerCase()); // abcdefg
document.write(str); // AbCdEfG

ABCDEFGabcdefgAbCdEfG

 

9. 수학연산

Math라는 기능을 이용하여 사용할 수 있는 연산들이다.

Math.abs(-3);
// Math.abs(n) : n을 절댓값으로 바꾼다.

Math.ceil(3.1);
// Math.ceil(n) : n값을 올림한다.

Math.floor(3.9);
// Math.floor(n) : n값을 내림한다.

Math.round(3.5);
// Math.round(n) : n값을 반올림한다.

var a = Math.random();
// Math.random() : 난수를 생성한다.

var b = Math.random()*10+10;
// Math.random()*x+y : y~x+y 범위에서 난수가 생성된다.

var c = Math.floor(Math.random() * (max - min)) + min;
// min 부터 max - 1 까지 범위의 난수

 

10. 형변환

// Num -> String
num = 2018;
var str = string(num);
var str = num.toString();

// String -> Num
var str = "2018.08";
var mInt = Number(str); // 2018
var mInt = parseInt(str); // 2018
var mFloat = parseFloat(str); // 2018.08

// JSON -> String
var myInfo = {
    name: '배진오',
    age: 24,
};
console.log(myInfo);
// 위와같이 출력하면 Object로 출력됨
console.log(JSON.stringify(myInfo));
// 위와같이 출력해야 문자열 JSON으로 출력됨

var myInfoStr = JSON.stringify(myInfo);
var transMyInfoToJSON = JSON.parse(myInfoStr);
// JSON 형식의 문자열이라면 parse를 이용해서 JSON으로 변환할 수 있음

 

반응형