[DAY3] JS 기초

유진·2023년 7월 29일
0
post-thumbnail

Function

  • calling / running / invoking function : 함수를 실행하다.

function declaration .vs function expression

  • 함수는 값이기도 하기 때문에 변수에 저장할 수 있다.

function declartaion

function calcAge1(birthYear){
	return 2037 - birthYear;
}

const age1 = calcAge1(1991);
console.log(age1);

function expression

const calcAge2 = function(birthYear){
	return 2037 - birthYear;
} // expression으로 값을 생성.

const age2 = calcAge2(1991);
console.log(age2)

차이점

  • function declaration(함수 선언)과 function expression(함수 표현식)의 가장 중요한 차이점은?
    함수 선언은 함수를 정의하기 전에 호출할 수 있다.
// function declaration
const age1 = calcAge1(1991);

function calcAge1(birthYear){
	return 2037 - birthYear;
}

console.log(age1);
// age1 출력 가능함.
// function expression
const age2 = calcAge2(1991);

const calcAge2 = function(birthYear){
	return 2037 - birthYear;
}

console.log(age2);
// 에러 발생.
  • 개인적인 취향에 따라 함수 선언이나 함수 표현식을 사용하면 된다.

arrow function

  • ES6에서 추가된 세 번째 유형의 함수
  • 특별한 형식의 function expression이다.
  • 더 빨리 함수를 작성할 수 있다.
const calcAge3 = birthYear => 2037 - birthYear;
// 간단한 한 줄의 함수에 대해서
// 중괄호가 필요 없고
// 반환이 암묵적으로 일어난다.

const age3 = calcAge3(1991);
console.log(age3);
const yearsUntilRetirement = birthYear => {
	const age = 2037 - birthYear;
	const retirement = 65 - age;
	return retirement;
}
// 코드가 두 줄 이상인 경우 return이 필요하다.

console.log(yearsUntilRetirement(1991));
const yearsUntilRetirement = (birthYear, firstName) => {
	const age = 2037 - birthYear;
	const retirement = 65 - age;
	return `${firstName} retires in ${retirement} years`;
}
// 매개변수가 두 개 이상인 경우 괄호가 필요하다.

console.log(yearsUntilRetirement(1991, 
'Jonas'));

함수 안에서 다른 함수를 호출하기

  • 한 함수가 내부에서 다른 함수를 호출하는 것은 매우 흔하다.
function cutFruitPieces(fruit){
	return fruit*4;
}

function fruitProceessor(apples, oranges){
	const applePieces = cutFruitPieces(apples);
	const orangePieces = cutFruitPieces(oranges);

	const juice = `Juice with ${applePieces} apples and ${orangePieces} oranges.`;
	return juice;
}

console.log(fruitProcessor(2,3));

Array

생성 방법

// 리터럴 구문, 대괄호 사용
const friends = ['Michael', 'Steven', 'Peter'];
// 키워드, Array 함 사용
const years = new Array(1991, 1984, 2008, 2020);

변경 방법


const friends = ['Michael', 'Steven', 'Peter'];

friends[2] = 'Jay'; // 변경됨. ['Michael', 'Steven', 'Jay']
// 주의: primitive value가 불변이라는 것이지, 배열은 primitive하지 않는다.
// 메모리 저장 방식과 관련이 있다. 추후 설명 예정.
friends=['Bob', 'Alice']; // ❌. 에러 발생함.

friends[4] = 'Eugene'; // 4번 인덱스에 값이 추가된다.

배열 연산 (메서드)

  • 배열에는 매우 많은 메서드가 있다.

push

  • 배열의 끝에 요소를 추가한다.

unshift

  • 배열의 시작에 요소를 추가한다.

pop

  • 배열의 마지막 요소를 제거한다.

shift

  • 배열의 시작 요소를 제거한다.

indexOf

  • 해당 요소가 위치한 인덱스를 반환한다. 없으면 -1을 반환한다.

includes

  • 해당 요소가 있으면 true를 반환하고 없으면 false를 반환한다.
  • 타입 변환이 되지 않는다. ‘23’과 23을 다르게 취급한다.

Object

  • 배열에서는 요소에 이름을 줄 방법이 없다. 인덱스로만 참조할 수 있다.
  • 이를 해결하기 위한 것이 객체이다. 객체에서 키 값 쌍을 정의하기 때문에 각각의 값에 이름을 줄 수 있다.
  • 값은 우리가 원하는 어떤 형식도 가능하다.
  • 키는 속성이라고도 한다.
  • 객체에서 요소의 순서는 배열과 달리 중요하지 않다. 그래서 비구조적인 데이터나 이름을 붙이길 원하는 데이터에 사용하기 좋다.
// 배열
const jonasArray = [
	'Jonas',
	'Schmedtmann',
	2037-1991
	'teacher',
	['Michael', 'Peter', 'Steven']
];

// 객체
const jonas = {
	firstName: 'jonas',
	lastName: 'Schmedtmann',
	age: 2037-1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven']
}; // 5개의 속성을 가진 jonas 객체

객체를 만드는 방법

  • 리터럴 구문, 중괄호 사용이 제일 흔하다.

데이터를 가져오는 방법

dot notation

  • .을 사용한다.
console.log(jonas.lastName); // Schmedtmann

bracket notation

  • []을 사용한다.
console.log(jonas['lastName']); // Schmedtmann
  • 응용 방법
const nameKey = 'Name';
console.log(jonas['first' + nameKey]);
console.log(jonas['first' + nameKey]);
const interestedIn = prompt("관심있는 것은? firstName, lastName, age, job, friends 중에 하나 작성");

if(jonas[interestedIn]){
	console.log(jonas[interestedIn]);
} else {
	console.log('Wrong request! Choose between firstName, lastName, age, job, and friends');

보통은 dot notation을 사용하고, 위의 응용 방법이 필요할 때(속성 이름을 계산해야 할 때) bracket notation 사용한다.

데이터를 추가하는 방법

const jonas = {
	firstName: 'jonas',
	lastName: 'Schmedtmann',
	age: 2037-1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven']
};

jonas.location = 'Portugal';
jonas['twitter'] = '@jonasschmedtman';
console.log(jonas); // location과 twitter 속성이 추가되어 있다.

객체 메서드

객체의 값으로 함수 설정하기

const jonas = {
	firstName: 'jonas',
	lastName: 'Schmedtmann',
	age: 2037-1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,

	calcAge: function(birthYear){
		return 2037 - birthYear
	},
};

console.log(jonas.calcAge(1991)); // 46
console.log(jonas['calcAge'](1991)); // 46
  • 함수를 객체의 값으로 할 수 있는 것처럼 메서드도 사실 속성이다.
  • 배열도 push 등의 메서드를 사용할 수 있는 거처럼 배열도 사실 객체이다.

응용 방법

const jonas = {
	firstName: 'jonas',
	lastName: 'Schmedtmann',
	birthYear: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,

//	calcAge: function(birthYear){
//		return 2037 - birthYear
//	},

	calcAge: function(){
		return 2037 - this.birthYear; // jonas.birthYear
	}
};

console.log(jonas.calcAge()); // 46
const jonas = {
	firstName: 'jonas',
	lastName: 'Schmedtmann',
	birthYear: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,

//	calcAge: function(birthYear){
//		return 2037 - birthYear
//	},

	calcAge: function(){
		this.age = 2037 - this.birthYear;
	}
};

jonas.calcAge();
console.log(jonas.age); // 46
const jonas = {
	firstName: 'jonas',
	lastName: 'Schmedtmann',
	birthYear: 1991,
	job: 'teacher',
	friends: ['Michael', 'Peter', 'Steven'],
	hasDriversLicense: true,

	calcAge: function(){
		this.age = 2037 - this.birthYear;
    return this.age
	},
  getSummary: function(){
    if (this.hasDriversLicense) console.log(`${this.firstName} is a ${this.calcAge()}-
		year old ${this.job}, and he has ${this.hasDriversLicense? 'a' : 'no'} driver's license`);
  }
};

jonas.getSummary(); // jonas is a 46-year old teacher, and he has a driver's license

Loop

loop 사용해 배열 만들기

const jonas = [
	'Jonas',
	'Schmedtmann',
	2037-1991,
	'teacher',
	['Michael','Peter','Steven'],
	true
];

const types = [];
for (let i=0 ; i<jonas.length ; i++){
	// Reading from jonas array
	console.log(jonas[i], typeof jonas[i]);

	// Filling type array
	types[i] = typeof jonas[i];
	// 또는 push 메서드를 사용할 수도 있다.
	// types.push(typeof jonas[i]);
}
console.log(types);
// typeof 응용하기

for (let i=0 ; i< jonas.length ; i++){
	if (typeof jonas[i] !== 'string') continue;

	console.log(jonas[i], typeof jonas[i]);
}
  • 배열 거꾸로 loop 돌리기
for (let i= jonas.length-1 ; i>=0 ; i--){
	...
}

0개의 댓글

관련 채용 정보