자바스크립트 메소드 정리

citron03·2022년 1월 14일
0

html, css, js

목록 보기
10/43

.splice(idx, delete count, ...insert);

  • splice는 배열에만 사용할 수 있다.
  • splice(시작 index, 시작 index로부터 제거할 원소의 갯수, 시작 index에 삽입할 원소들);
  • 원본 배열을 편집하고, 삭제한 원소를 배열에 담아 반환한다.
let a = [1, 2, 3, 4, 5];

console.log(a.splice(1, 3, 'a', 'A', 9));
// [2, 3, 4] 이 출력된다.

console.log(a);
// [1, 'a', 'A', 9, 5] 이 출력된다.

.slice(start, end);

  • slice는 배열과 문자열에 모두 사용할 수 있다.
  • 원본 배열을 수정하지 않고, 해당 위치의 원소만 복사한 배열 / 문자열을 반환한다.
let a = [1, 2, 3, 4, 5];
let b = "hi i am james";

console.log(a.slice(2, 4)); // [3, 4] 출력
console.log(b.slice(5, 7)); // am 출력

console.log(a);
console.log(b);
// 원본은 수정되지 않는다.

.concat(배열);

  • concat으로 두 개의 배열을 합칠 수 있다.
  • 앞에 오는 배열의 뒤에 매개변수로 받는 배열을 그대로 붙인다.
let a = ['a', 'ff', 'yy'];
let b = [1, 2, 343];

console.log(a.concat(b));
// ['a', 'ff', 'yy', 1, 2, 343]

.flat(평탄화할 중첩 배열의 수);

  • flat은 중첩배열을 평탄화한다.
  • 내부에 인자로 평탄화할 중첩배열의 수를 정할 수 있다.
  • Infinity를 사용함으로써, 모든 내부의 중첩 배열을 일차원 배열로 평탄화한다.
let a = [1, [2, [3, [4, [5]]]]];
let b = a.flat(3);
console.log(b);
// [1, 2, 3, 4, [5]] 가 출력된다.

let c = a.flat(Infinity);
console.log(c);
// [1, 2, 3, 4, 5] 가 출력된다.

.fill(배열을 초기화할 값)

  • new Array(원소 개수); 로 배열을 만들 수 있다.
  • fill을 이용해 내부에 값을 초기화 할 수 있다.
// 모든 원소가 0인 3 * 3 배열을 만든다.
let a = [];
for(let i = 0 ; i < 3; i++)
	a.push(new Array(3).fill(0));

for(rows of a)
   console.log(rows);
/*
출력되는 값은 다음과 같다.
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
*/

.reverse()

  • reverse()를 사용하면 배열을 뒤집는다.
let array = [1, -2, 3, 100];
let reverse = array.reverse();

console.log(reverse);
// [100, 3, -2, 1] 이 출력된다.

.sort(함수)

  • 배열을 오름차순으로 정렬한다.
  • sort는 문자를 기준으로 정렬하기 때문에, 숫자로 정렬하기 위해서는 (a, b) => a - b 와 같은 함수를 사용해야 한다.

let a = ['d', 'a', 'c' , 'b'];
a.sort();
console.log(a); //  ['a', 'b', 'c', 'd'] 출력

let b = [3, 56, 2, -4, 0];
b.sort((a, b) => a - b);
console.log(b); // [-4, 0, 2, 3, 56] 출력

b.reverse(); // 내림차순으로 변경
console.log(b); // [56, 3, 2, 0, -4] 출력

.startsWith(문자열) 과 .endsWith(문자열)

  • 해당 문자열이 인자로 받은 문자열로 시작하는지 / 끝나는지 확인한다.
  • true나 false를 리턴한다.
console.log('#hello world'.startsWith("#")); // true
console.log('#hello world'.startsWith("#hello")); // true
console.log('#hello world'.startsWith("#bye")); // false

console.log('#hello world!!'.endsWith("!")); // true
console.log('#hello world!!'.endsWith("world!!")); // ture
console.log('#hello world!!'.endsWith("world~~")); // false

.includes(찾을 값)

  • 배열이나 문자열에서 원소가 있는지 확인하고 true나 false를 반환한다.
console.log('and'.includes('d')); // true
console.log('and'.includes('q')); // false

console.log([1, 4, 5].includes(5)); // true
console.log([1, 4, 5].includes(40)); // false

.indexOf(찾을 원소)

  • 배열 또는 문자열에 사용할 수 있는 메소드로 원소의 인덱스를 반환한다.
  • 만약 못찾는다면, -1를 반환한다.
let a = 'abc';
let b = [1, 2, 3];

console.log(a.indexOf('a')); // 0
console.log(a.indexOf('g')); // -1

console.log(b.indexOf(3)); // 2
console.log(b.indexOf(120)); // -1

.split(문자열)과 .join(문자열)

  • 두 메소드는 매개변수를 기준으로 문자열을 나누고 합칠 수 있다.
  • split의 결과로 문자열에서 배열이 만들어진다.
  • join은 배열을 문자열로 만든다.
  • 인자로 빈 문자열을 사용할 시, 원소 하나 하나를 모두 분해하고 붙인다.
// case 1 //
let a = 'abcdhfsj';
let b = a.split('');
console.log(b); 
// ['a', 'b', 'c', 'd', 'h', 'f', 's', 'j'] 이 출력된다.

b = b.join('');
console.log(b);
// abcdhfsj 이 출력된다.

// case 2 //
let str = "Hello i am student";
str = str.split(" ");
console.log(str);
// ['Hello', 'i', 'am', 'student'] 이 출력된다.

str = str.reverse(); // 현재 배열인 상태이기에 배열과 관련된 메소드가 실행 가능하다.
console.log(str);
// ['student', 'am', 'i', 'Hello'] // 이 출력된다.

str = str.join(" ");
console.log(str);
// student am i Hello 이 출력된다.

.substr(from, length);

  • substr로 문자열을 나눌 수 있다. from 부터 length 개의 문자열을 잘라 반환한다.
  • 원본 문자열에는 영향이 없다.
  • 이를 통해서 중간의 문자를 삭제할 수 있다.
let a = "abcde";
let b = a.substr(1, 2);
console.log(a); // abcde
console.log(b); // bc

// c만 제거하기
let c = a.substr(0,2) + a.substr(3, 2);
console.log(c); // abde

.toUpperCase() 와 .toLowerCase()

  • 이 두 메소드를 이용해서 알파벳을 대문자, 소문자로 변환할 수 있다.
let a = 'aaa';

a = a.toUpperCase();
console.log(a); // AAA 출력

a = a.toLowerCase();
console.log(a); // aaa 출력

Math 라이브러리

Math.round(N);

숫자 N을 반올림 한다.

Math.floor(N);

숫자 N을 버림한다.

Math.ceil(N);

숫자 N을 올림한다.

console.log(Math.round(1.123123));
// 1

console.log(Math.round(1.5));
// 2

console.log(Math.floor(1.123123));
// 1

console.log(Math.ceil(1.123123));

Math.max(...array);

주어진 숫자들에서 최대값을 찾는다.

Math.min(...array);

주어진 숫자들에서 최솟값을 찾는다.

// 이차원 배열에서 최대, 최솟값 찾기
let a = [[1, 2, 3], [100, 200, 300], [-10, 600, 0]];

const max = Math.max(...a.flat(Infinity));
console.log(max);
// 600

const min = Math.min(...a.flat(Infinity));
console.log(min);
// -10

// 배열에서 최대, 최소값을 찾기위해선, 전개구문을 이용한다. 
profile
🙌🙌🙌🙌

0개의 댓글