티스토리 뷰

JS

javascript #2 반복문, 함수

0307kjb 2022. 1. 9. 21:52

for, do while, while 등..

 

js에서의 특이 반복문 :

// for of

for(const i of [1, 2 ,3]){
	console.log(i); => // 1,2,3 출력
}


// for in

Object.prototype.test = function(){};

for(const i in {a : 1, b : 2, c:3}){
	console.log(i); => // a,b,c, test(?) 출력 => 조심해서 사용하자!
}

 

함수)

//선언적 function

function hello1(){
	console.log('hello1');
}

console.log(hello1, type of hello1); // [Function : hello1], 'function' 

// 매개변수와 함수 호출할 때 값을 지정
function hello2(name){
	console.log('hello2', name);
}

// 함수의 리턴
// 함수를 실행하면 얻어지는 값
function hello3(name){
	return'hello3 ${name}';
}

------------------------------------------------------------------------------------------

// 익명함수 만들어 변수 할당. + 호이스팅 안됨.

const hello4 = function(){
	console.log('hello4');
},

const hello5 = function(name){
	console.log('hello5', name);
}

const hello6 = function(name){
	return'hello6 ${name}';
}

// 자주 쓰이진 않는..?
const hello7 = new Function(매개변수, 매개변수 ... , '함수 몸체');

ex)
const sum = new Function('a','b','c', 'return a + b + c');
console.log(sum(1,2,3)); => // 6


es6 version after)

const hello7 = () => {
	console.log('hello7');
}

const hello8 = (name) => {
	console.log('hello8',name);
}

const hello8 = name => 'hello8 ${name}' // return 생략!

--------------------------------------------------------------------------------------------
// 생성자 함수

function Person(name , age){
	this.name = name; // 먼저 넣어 줘야한다 이전에 console.log(this)하면 에러.
    this.age = age;
}

const p = new Pesson('mark',27);
console.log(p, p.name, p.age); // Person{ name : 'mark', age : 27 } 'mark' 27


function plus(base){
	return function(num){
    	return base + num;
    }
}

const plus5 = plus(5);
console.log(plus5(10)); // 15
const plus7 = plus(7);
console.log(plus7(8)); // 15


function hello(c){
	console.log('hello');
    c();
}

hello(function(){
	console.log('콜백'); // hello \n 콜백
});

'JS' 카테고리의 다른 글

javascript #6 Promise  (0) 2022.01.10
javascript #5 클래스  (0) 2022.01.10
javascript #4 표준 내장 객체 Array  (0) 2022.01.09
javascript #3 함수, 프로토타입  (0) 2022.01.09
javascript #1 변수  (0) 2022.01.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함