JavaScript문법 정리

노지수·2022년 12월 1일
0

검색규칙

  1. 띄어쓰기없이 사용
  2. @붙여서 검색

@비구조할당

(@구조분해할당, @배열구조분해, @객체구조분해)

- 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript의 표현식.

  • 객체 구조분해
const animal = {
    name : '멍멍이',
    type : '개'
}

const {name, type} = animal;

console.log(name);
console.log(type);

/* 객체의 깊숙한곳에 있는 값을 꺼내는법 */
const deepObject = {
    state : {
        information : {
            name : 'jibbang',
            languages : ['korean', 'english']
        }
    },
    value : 5
}

const {name, languages} = deepObject.state.information;
const {value} = deepObject;

console.log(name);

  • 배열 구조분해
const animal = ['강아지', '고양이'];
const [dog, cat] = animal;

console.log(dog);

@spread

- 객체 혹은 배열을 펼치다.(객체나 배열을 통채로 가져와서 사용가능)

- 기존의 객체나 배열은 건들지 않고 새로운 객체를 만들때 사용

  • 객체에서의 spread
const pet = {
    dog : '개',
    cat : '고양이'
}

const animal = {
    ...pet,
    tigger : '호랑이'
}

console.log(animal);

  • 배열에서의 spread
const oneTwo = [1, 2];
const number =[...oneTwo, 3, 4];

console.log(number);

@rest

- 구조분해 문법과 같이 사용시 나머지(객체 혹은 배열)를 rest에 담아서 추출가능.

- 함수의 파라미터로 사용시 함수에서 정해지지않은 수의 파라미터를 배열로 받을 수 있다.

  • 객체에서의 rest
const animal = {
    dog: '개',
    cat: '고양이',
    tigger: '호랑이'
}

const {dog, ...rest} = animal;

console.log(dog);
console.log(rest);

  • 배열에서의 rest
const number = [1, 2, 3, 4];

const [one, two, ...rest] = number;

console.log(one);
console.log(two);
console.log(rest);

  • 함수의 파라미터에서의 rest
function total(...rest) {
    return rest;
}

const result = total(1, 2, 3, 4);

console.log(result);

@배열내장함수

(@배열함수, @배열의내장함수, @배열의함수)

@length

- 배열의 길이를 return한다.

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

console.log(number.length);	// 4

@forEach

- 배열을 순회하는 함수 중 하나. 배열을 순회하기 위해서는 함수가 필요하며 배열의 요소를 나타내는 파라미터를 반드시 하나 이상 사용해야한다.
(선택적 매개변수로는 index(각 요소의 index번호)와 array(해당 배열)가 있다.)

const animals = ['개', '고양이', '토끼', '거북이'];

animals.forEach(animal => {
	console.log(animal);
});
// 개, 고양이, 토끼, 거북이 가 각각 출력됨

@map

- 배열에 있는 모든 요소들의 값을 변경해서 새로운 배열을 만들때 사용한다.
(선택적 매개변수로 index(각 요소의 index번호)와 array(해당 배열), this(콜백함수내부에서 사용)가 있다.)
arr.map(function(element, index, array), this);

const number = [1, 2, 3, 4, 5];

const newNumber = number.map(n => n * n);

console.log(newNumber);	// [1, 4, 9, 16, 25]

@indexOf

- 배열에서 특정 조건을 만족하는 첫번째 요소의 index를 return한다.
- 찾는 요소가 없으면 -1을 return한다.
arr.indexOf(element, index);

const animals = ['개', '고양이', '거북이', '토끼'];

console.log(animals.indexOf('고양이'));	// 1

@findIndex

- 배열에서 특수한 조건에 대해서 만족하는 첫번째 요소릐 index를 return한다.
- 조건에 맞는 요소를 찾을 수 없다면 -1을 return한다.
(선택적 매개변수로 index(각 요소의 index번호)와 array(해당 배열), this(콜백함수내부에서 사용)가 있다.)
arr.findIndex(function(element, index, array), this);

const todos = [
  {
  	id: 1,
    text: 'java',
    done: true
  },
  {
  	id: 2,
    text: 'javascript',
    done: true
  },
  {
  	id: 3,
    text: 'react',
    done: true
  },
  {
  	id: 1,
    text: 'spring',
    done: false
  }
]

const index = todos.findIndex(todo => todo.id === 3);
console.log(index);	// 2

@find

- 배열에서 조건에 만족하는 첫번째 요소(객체)를 return한다.
- 조건에 맞는 요소를 찾을 수 없다면 undefined를 return한다.
(선택적 매개변수로 index(각 요소의 index번호)와 array(해당 배열), this(콜백함수내부에서 사용)가 있다.)
arr.find(function(element, index, array), this);

const todos = [
  {
  	id: 1,
    text: 'java',
    done: true
  },
  {
  	id: 2,
    text: 'javascript',
    done: true
  },
  {
  	id: 3,
    text: 'react',
    done: true
  },
  {
  	id: 1,
    text: 'spring',
    done: false
  }
]

const todo = todos.find(todo => todo.id === 3);
console.log(todo);	// {id: 3, text: 'react', done: true}

@filter

- 배열에서 오름차순으로 접근해 조건을 만족하는 요소들로 새로운 배열을 return한다.

const todos = [
  {
  	id: 1,
    text: 'java',
    done: true
  },
  {
  	id: 2,
    text: 'javascript',
    done: true
  },
  {
  	id: 3,
    text: 'react',
    done: true
  },
  {
  	id: 1,
    text: 'spring',
    done: false
  }
]

const.taskNotDone = todos.filter(todo => todo.done === false);
console.log(taskNotDone);	// {id: 4, text: 'spring', done: false}

@splice

- 배열에서 특정 요소를 제거하는 함수(기존 배열을 변경한다.)

const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30);
const spliced = numbers.splice(index, 2);	// index부터 2개 지우겠다.
//지운값[30, 40]이 spliced에 저장된다.
console.log(spliced);	// [30, 40]
console.log(numbers);	// [10, 20] -> 기존 객체가 변경된다.

@slice

- 배열에서 시작과 끝을 지정하여 새로운 배열을 return한다.(기존배열을 변경하지 않는다.)

const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0, 2);	// '0'번 index로부터 '2'번 index전까지만 선택된다.
console.log(sliced);	// [10, 20]
console.log(numbers);	// [10, 20, 30, 40]

@shift

- 배열에서 가장 첫번째의 원소를 추출한다.(기존배열이 변경된다.)

const numbers = [10, 20, 30, 40];

const value = numbers.shift();

console.log(value);		// 10
console.log(numbers);	// [20, 30, 40]

@unshift

- 배열에서 가장 첫번째에 원소를 추가한다.

const numbers = [10, 20, 30, 40];
numbers.unshift(5);

console.log(numbers);	// [5, 10, 20, 30, 40]

@pop

- 배열에서 가장 마지막의 원소를 추출한다.(기존배열이 변경된다.)

const numbers = [10, 20, 30, 40];
const value = numbers.pop();

console.log(value);		// 40
console.log(numbers);	// [10, 20, 30]

@push

- 배열에서 가장 마지막에 원소를 추가한다.(기존 배열이 변경된다.

const numbers = [10, 20, 30, 40];
numbers.push(50);

console.log(numbers);	// [10, 20, 30, 40, 50]

@concat

- 배열과 요소(배열)을 합쳐서 새로운 배열을 만든다.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const array1 = arr1.concat(arr2);
const array2 = arr1.concat(4);

console.log(array1);	// [1, 2, 3, 4, 5, 6]
console.log(array2);	// [1, 2, 3, 4]

@join

- 배열을 기준에 따라 문자열로 바꿔서 return한다.(,가 기본값)

const array = [1, 2, 3, 4, 5];

console.log(array.join());		// 1,2,3,4,5
console.log(array.join(' '));	// 1 2 3 4 5
console.log(array.join('-'));	// 1-2-3-4-5

@reduce

- 배열의 각 요소에 대해 주어진 reducer함수를 실행하고, 하나의 결과값을 return한다.
- 반환하는 값은 객체일 수도 있고, 다른 배열일 수도 있다.
- 배열이 주어졌을때 배열안에 모든값을 사용하여 연산할때 사용한다.

  • 배열안의 값의 총합
const numbers = [1, 2, 3, 4, 5];
/*
const sum = arr.reduce((누적연산값, 현재index의 데이터값) => {
	누적연산값 + 현재index데이터
}, 누적연산기본값);
*/
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum);	// 15

  • 배열안의 값의 평균
const numbers = [1, 2, 3, 4, 5];
/*
const avg = arr.reduce((누적연산값, 현재index의 데이터값, current의 index, arr배열) => {
	연산과정
}, 누적연산기본값);
*/
const avg = numbers.reduce((accumulator, current, index, array) => {
	if(index === array.length - 1){
    	return (accumulator + current) / array.length;
    }
  	return accumulator + current;
}, 0);
console.log(avg);	// 3

  • 배열안의 각 알파벳이 몇개가 있는지 카운트해서 객체에 넣어주기
const alphabets = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e'];
const counts = alphabets.reduce((acc, current) => {
	if(acc[current]) {	// acc['a'] === acc.a
    	acc[current] += 1;	// acc.a += 1
    }else {
    	acc[current] = 1;
    }
  	return acc;
}, {});	// acc의 초기값 {} (빈객체)

console.log(counts);	// {a: 3, b: 1, c: 2, d: 1, e: 1}
profile
프로그래밍, 개념 및 이론 기록

0개의 댓글