JS내장함수(배열, etc)

jini.choi·2022년 5월 17일
0

JavaSctipt-입문

목록 보기
6/10

repeat

  • 특정 문자열을 지정한 횟수만큼 반복해서 새로운 문자열을 생성
  • 인수는 양수인 정수로 입력(음수X)
const str = "string";
const n = 5;
const result = str.repeat(n);

console.log(result); // 출력: "stringstringstringstringstring"

parseInt

  • string→number타입으로 변환

forEach

  • 배열 안에 있는 원소들을 가지고 어떤 작업을 일괄적으로 하고 싶을 때
const superheros = ["아이언맨", "캡틴", "토르", "닥터스크레인지"];

superheros.forEach((hero)=>{
	console.log(hero);
});

/* 결과
for ( let i = 0; i < superheros.length; i++) {
   console.log(superheros[i])
}
*/ 

map

  • 배열이 있을 때 전체적으로 변환을 해주고 싶을 때 사용하는 내장함수
const array = [1, 2, 3, 4, 5, 6, 7, 8];

const sqaured = array.map(n => n* n);

console.log(sqaured); //[1, 4, 9, 16, 25, 36, 49, 64]

indexOf

  • 특정 항목이 배열에서 몇번째 원소인지 알고 싶을 때
const superheros = ["아이언맨", "캡틴", "토르", "닥터스크레인지"];

const index = superheros.indexOf('토르');
console.log(index);

findIndex

  • 배열안에 있는 값들이 객체이거나, 특정 조건이 있는 배열 요소들 중 몇번때인지 찾아야 될 때
const todos = [
	{
		id: 1,
		text: '자바스크립트 입문',
		done: true
	},
	{
		id: 2,
		text: '함수 배우기',
		done: true
	},
	{
		id: 3,
		text: '객체와 배열 배우기',
		done: true
	},
	{
		id: 4,
		text: '배열 내장함수 배우기',
		done: false
	},
];

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

//find()는 객체, 원소 그 자체를 출력함
//indexOf, find, findIndex 같은 경우 가장 첫번째로 찾은 그런 항목을 알려준다
const todo = todos.find(todo => todo.done === false);
console.log(todo);
/** 결과
//[object Object]
{
	id: 4,
	text: '배열 내장함수 배우기',
	done: false
}
*/

filter

  • 특정 조건을 만족하는 원소들을 찾아서 그 원소들을 가지고 새로운 배열을 만드는 함수
const taskNotDone = todos.filter(todo => !todo.done);
console.log(taskNotDone);
//[{id:4, text:"배열 내장함수 배우기", done: false}]

splice

  • 배열 내의 특정한 요소를 삭제하거나, 다른 요소로 대치하거나 새로운 요소를 추가할 때 사용

  • splice(배열의 index의 시작점, 삭제할 요소의 개수, 추가하고 싶은 요소)

  • 댓글 삭제 기능 구현 시 많이 활용 됨

  • 예를 들어, [1, 2, 3, 4, 5] 라는 배열에서 숫자 3을 제거하고 그 자리에 10을 추가하려고 함

const num = [1, 2, 3, 4, 5];
num.splice(2, 1, 10);
console.log(num); // [ 1, 2, 10, 4, 5 ]
  • 아래와같이 제거를 하게되는 과정에서 해당 원소가 몇번 째인지 따로 명시해서 활용 가능
const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30);//몇번째인지 명시
const spliced = numbers.splice(index,2);//index부터 몇개를 지워라
console.log(spliced);//[30, 40]//지운거
console.log(numbers); //[10, 20]//남은거

slice

  • 배열을 잘라내는데 기존 배열은 건들이지 않는다.
const numbers = [10, 20, 30, 40];
const slised = numbers.slice(0, 2); //0부터 2전까지 자른다.
console.log(slised); //[10, 20] //자른거
console.log(numbers); //[10, 20, 30, 40]//기존 배열 그대로
  • 첫번째 인자에 음수가 들어가는 경우 끝에서부터 해당하는 숫자 만큼의 요소를 배열에 담아 리턴
const nums = [1, 2, 3, 4, 5];
const nums_new = nums.slice(-2);

console.log(nums) // [1, 2, 3, 4, 5]
console.log(nums_new) // [4, 5]

unshift, shift

  • 하나의 쌍
const numbers = [10, 20, 30, 40];
numbers.unshift(5); //배열 맨 앞에 추가
const value = numbers.shift(); //배열 맨 앞에서 추출, 배열수정
console.log(value); //5 //추출한거
console.log(numbers); //[10, 20, 30, 40] // 남은 배열

push, pop

  • 하나의 쌍
const number = [10, 20, 30, 40];
number.push(50); //배열 맨 뒤에 추가
const value = numbers.pop(); // 배열 맨 뒤에서 추출, 배열 수정
console.log(value); //50 //추출한거
console.log(numbers); //[10, 20, 30, 40] //남은 배열

concat

  • 여러 개의 배열을 하나의 배열로 합쳐주는 함수, 기존 배열 건드리지 않음
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];

const concated = arr1.concat(arr2,arr3);
console.log(concated); //[1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(arr1); //[1, 2, 3]
console.log(arr2); //[4, 5, 6]
console.log(arr3); //[7, 8, 9]

// const concated2 = [...arr1, ...arr2]; //스프레드연산자(ES6)
// console.log(concated2);

join

  • 배열 안에 있는 값들을 문자 형태로 합쳐주는 함수
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

  • 배열이 주어졌을 때 배열 안에 있는 모든 값들을 사용하여 어떤 값을 연산해야 할 때 사용
const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(
(accumulator, current) => accumulator + current, 0
);

console.log(sum); //15
  1. 초기 accumulator(누적된 값) 0이, accumulator가 된다.
  2. current(각 원소들)를 가르키게 되는데 처음엔 1이 들어가지게 됨
  3. 그럼 0, 1이 된다 ⇒ 0 + 1 = 1
  4. 돌아서 1accumulator가 됨
  5. 그럼 accumulator === 1, current === 2가 됨 ⇒ 1 + 2 = 3 .... 각 배열 원소를 다 쓸 때까지 돔
  6. 최종적으로
    accumulator === 10, current === 5 => accumulator + current15

평균 구하기

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

const avg = numbers.reduce((accumulator, current, index, array) => {
		if(index === array.length - 1){ //조건 맞을때까지 2번 리턴만 실행 // -1하는 이유는 length가 5이고 index가 4이기 때문에 맞추는 것
			return (accumulator + current) / array.length;	//1번
		}
		return accumulator + current; //2번
	}, 0);

console.log(avg);

index - 배열의 몇번째 원소인지
array- 우리가 함수를 실행하고 있는 자기 자신을 의미(numbers)


알파벳 갯수 세기

const alphabets = ['a', 'a', 'a', 'b', 'c', 'c', 'd', 'e'];

const counts = alphabets.reduce((acc, current) => {
	if(acc[current]){
		acc[current] += 1;
	}else{
		acc[current] = 1;	
	}
	return acc;
}, {}); //1.{}:코드블럭 2.{}:빈객체

console.log(counts); //{a:3,b:1,c:2,d:1,e:1}

{}: 초기엔 빈객체가 acc,
1. acc[current]가 a가 아니므로 a= 1
2. acc[current]가 a니깐 a+1을 함 * 2 = a === 3
3. acc[current] a가 아니므로 b = 1
4. acc[current]가 b가 아니므로 c = 1
5. acc[current]가 c니깐 c+1을 함 = c === 2
6. acc[current]가 c가 아니므로 d = 1
7. acc[current]가 d가 아니므로 e = 1
8. 배열이 다 연산되어 출력 { a: 3, b: 1, c: 2, d: 1, e: 1 }


이 글은 패스트캠퍼스 '프론트엔드(React)올인원패키지Online'을 수강하며 정리한 노트입니다.
https://fastcampus.co.kr/search?keyword=%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C

profile
개발짜🏃‍♀️

0개의 댓글