JavaScript

JavaScript 기본 다시보기

amungstudy 2024. 1. 31. 15:29

React와 Nodejs 학습을 위해 JavaScript를 다시 보고 있다.

함수

-함수 표현식 : 호이스팅의 대상에 허용되지 않는다.

let hello = function(){
  return '안녕하세요 여러분';
}; // 함수 표현식
// 변수에 함수를 담을때는 함수에 이름이 없어도 된다.

const helloText = hello(); // 함수의 리턴값이 담긴다
console.log(helloText);

람다함수로도 사용 가능

let helloA = () => {
  return "안녕하세요 여러분"; 
};
console.log(helloA());

리턴만 있는 경우 다음과 같이 축약 가능

let helloA = () => "안녕하세요 여러분";

-함수 선언식 : 호이스팅의 대상

function helloB() {
  return "안녕하세요 여러분";
} // 함수 선언식

객체

객체 생성 방법 - 객체 리터럴 방식이 주로 쓰임

let person = new Object(); // 생성자 방식
let person = {}; // 객체 리터럴 방식
let person = {
  key: "value", // 프로퍼티(객체 프로퍼티)
  key1: 123,
  key2 : true,
  key3 : undefined,
  key4 : [1,2],
  key5 : function(){}
}; // 객체 리터럴 방식

객체 접근 방법 2가지 - 점표기법, 괄호표기법

괄호표기법은 동적인 파라미터를 꺼내오거나 키가 고정되어있지 않은 상황일때 사용함.

console.log(person.name); 
console.log(person["name"]); // 반드시 키를 문자열형태로 넣는다
// 동적인 파라미터를 꺼내오거나 키가 고정되어있지 않은 상황일때 쓴다.
console.log(getPropertyValue("name"));

function getPropertyValue(key) {
  return person[key];
}

객체 괄호 표기법 응용

const getMeal1 = (mealType) =>{
  if(mealType == "한식") return "불고기";
  if(mealType == "양식") return "파스파";
  if(mealType == "중식") return "멘보샤";
  if(mealType == "일식") return "초밥";
  return "굶기";

}

아래와 같이 변경 가능

const meal = {
  한식 : "불고기",
  중식 : "멘보샤",
  일식 : "초밥",
  양식 : "스테이크",
  인도식 : "카레"
}

const getMeal  = (mealType) =>{
  return meal[mealType] || "굶기";
}
console.log(getMeal("일식"));

객체의 수정, 삭제

const person = {
  name: "이정환",
  age: 25
}; // 객체 리터럴 방식

// 프로퍼티 추가
person.location = "한국";
person['gender'] = "남성";

// 프로퍼티 수정
person.name = "이정환A";

// 프로퍼티 삭제
person.name = null;

delete 명령어로 삭제하면 메모리는 그대로 남아있어서 null을 대입하는것이 더 좋다.

메서드가 아닌 프로퍼티는 멤버라고 부른다.

const person = {
  name: "이정환", // 멤버
  age: 25, // 멤버
  say: function(){
    console.log(`안녕나는 ${this.name}`);
  } // 메서드 
}; // 객체 리터럴 방식

// 객체 메서드 호출
person.say();
person["say"]();

객체 내에 해당 프로퍼티가 있는지 확인하는 방법 : in 연산자 활용(boolean으로 반환)

console.log(`name : ${"name" in person}`)
// 출력값: name : true

객체를 순회해보자(Object.keys(변수이름))

let person = {
  name: "이정환",
  age: 25,
  tall: 175
};
// 객체의 키를 배열로 반환
const personKeys = Object.keys(person);
console.log(personKeys);

for(let i=0; i<personKeys.length; i++){
  console.log(personKeys[i]);
}

key를 가지고 value 출력

// 객체의 키를 배열로 반환
const personKeys = Object.keys(person);

for(let i=0; i<personKeys.length; i++){
    const curKey = personKeys[i];
    const curValue = person[curKey]; // key를 이용해서 value에 접근
    console.log(`${curKey} : ${curValue}`);
}

객체의 value만 배열 형태로 반환하는 Object.values(변수이름); 도 있다.

const personValues = Object.values(person);
for(let i = 0; i< personValues.length; i++){
  console.log(personValues[i]);
}

배열

배열 생성 두가지 방법

let arr1 = new Array();
let arr2 = [];

배열엔 다양한 타입이 들어갈 수 있음

                                    // 객체, 배열, 함수
let arr = [1,"2",true,null,undefined,{},[],function(){}];
console.log(arr);

배열에 값 추가하기(push메서드)

let arr = [1,2,3,4,5];

// 배열의 마지막에 원소 추가
arr.push(6);
arr.push({key:"value"});
console.log(arr.length); // 배열 길이 출력

배열 내장함수 이용

forEach() : 배열의 각각의 요소에 대해 실행한다

for(let i = 0 ; i<arr.length; i++){
  console.log(arr[i]);
}
//위와 같다
arr.forEach((elm)=> console.log(elm));

// 함수형으로 바꿔보면
arr.forEach(function (elm){
  console.log(elm);
})

map() : 원본 배열의 모든 요소를 순회하면서 어떤 연산을 해서 리턴된 값만 따로 추려내서 반환해줌

const arr = [1, 2, 3, 4];

const arr1 = [];
arr.forEach((elm) => arr1.push(elm * 2));

// 위와 같다
const newArr = arr.map((elm)=>{
  return elm*2;
})

console.log(newArr);

includes() : 배열에 전달받은 인자와 일치하는 값이 존재하는지 boolean타입으로 반환(===연산을 사용한다(타입까지 비교))

const arr = [1, 2, 3, 4];

let number = 3;
arr.forEach((elm)=>{
  if(elm === number){
    console.log(true);
  }
});
//위와 같다
console.log(arr.includes(number));

응용 v1

function isKoreanFood(food){
  if(["불고기","떡볶이","비빔밥"].includes(food)){
    return true;
  }
  return false;
}

const food1 = isKoreanFood("불고기");
const food2 = isKoreanFood("파스타");
console.log(food1);
console.log(food2);

indexOf() : 전달받은 인자와 일치하는 값의 인덱스번호를 반환한다. (===연산을 사용한다(타입까지 비교))

const arr = [1, 2, 3, 4];

let number = 3;
console.log(arr.indexOf(number)); // 2

객체배열에서 찾기 -> findIndex() : 콜백함수가 true인 인덱스 번호 반환
만약 배열에 두가지 이상 일치하는 값이 있는 경우 제일 처음 만난 인덱스 반환

const arr = [
  {color: "red"},
  {color: "black"},
  {color: "blue"},
  {color: "green"}
];

console.log(arr.findIndex((elm)=>elm.color === "green")); // 3

// 위와 같다
console.log(arr.findIndex((elm)=> {
  return elm.color === "green"})); // 3

find() : 조건에 일치하는 요소를 가져온다

const idx = arr.findIndex((elm)=> {
  return elm.color === "green"});

console.log(arr[idx]); // {color: "green"}

// 위 와 같다
const element = arr.find((elm)=> elm.color ==="green");
console.log(element); // {color: "green"}

filter() : 배열 필터링 : 배열에서 특정한 조건을 만족하는 요소를 배열 형태로 반환

const arr = [
  { num: 1, color: "red" },
  { num: 2, color: "black" },
  { num: 3, color: "blue" },
  { num: 4, color: "green" }
];

console.log(arr.filter((elm) => elm.color === "blue"));

slice() : 잘린 배열을 새로운 배열로 반환


const arr = [
  { num: 1, color: "red" },
  { num: 2, color: "black" },
  { num: 3, color: "blue" },
  { num: 4, color: "green" }
];

console.log(arr.slice(0,2)); // end-1까지 반환 
// 출력값 : (2) [Object, Object]

concat() : 배열 붙여서 새로운 배열로 반환

const arr1 = [
  { num: 1, color: "red" },
  { num: 2, color: "black" },
  { num: 3, color: "blue" },
];

const arr2 = [
  { num: 4, color: "green" },
  { num: 5, color: "blue" },
];

console.log(arr1.concat(arr2)); 
// arr1의 마지막인덱스 뒤에 arr2 붙임

sort() : 원본배열을 사전순으로 정렬

숫자를 정렬할때는 비교함수를 만들어서 전달해야함

let chars = ["나", "다", "가"];
chars.sort();
console.log(chars); // ["가", "나", "다"]

let numbers = [0, 1, 3, 2, 10, 30, 20];

const compare = (a, b) => {
  // 1. 같다
  // 2. 크다
  // 3. 작다
  if (a > b) {
    // 크다
    return 1; // a를 뒤로 보낸다
  }
  if (a < b) {
    // 작다
    return -1; // a를 앞으로 보낸다
  }
  // 같다
  return 0; // 옮기지 않는다
};

numbers.sort(compare);
console.log(numbers); // [0, 1, 2, 3, 10, 20, 30]

join() : 배열 요소들을 문자열로 합쳐서 반환한다.

const arr = ["이정환","님","안녕하세요","또오셨네요"];
console.log(arr.join()); // 구분자를 안넣으면 ","로 구분
// 이정환,님,안녕하세요,또오셨네요 
console.log(arr.join(" ")); // 이정환 님 안녕하세요 또오셨네요 
console.log(arr.join("==="));

본 게시글은 아래 강의를 참고하였습니다.

https://www.inflearn.com/course/%ED%95%9C%EC%9E%85-%EB%A6%AC%EC%95%A1%ED%8A%B8/dashboard

[한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지 강의 - 인프런

개념부터 독특한 프로젝트까지 함께 다뤄보며 자바스크립트와 리액트를 이 강의로 한 번에 끝내요. 학습은 짧게, 응용은 길게 17시간 분량의 All-in-one 강의!, 리액트, 한 강의로 끝장낼 수 있어요.

www.inflearn.com](https://www.inflearn.com/course/%ED%95%9C%EC%9E%85-%EB%A6%AC%EC%95%A1%ED%8A%B8/dashboard)