[ TIL ] javascript 기본 메서드

Gorae·2021년 7월 9일
0

(TIL) Javascript

목록 보기
1/3
post-thumbnail

1. Array 메서드

1. pop, push

  • pop, push의 처리 속도가 unshift, shift 보다 빠르다.

pop

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

  • pop() 메서드는 배열 마지막 요소를 제거하고, 그 요소를 반환한다.
  • 빈 배열에 pop() 호출 시 undefined 를 반환한다.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]

push

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.
const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

2. shift, unshift

  • shift, unshift 의 처리 속도가 push, pop 보다 느리다.

shift

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

  • shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환한다.
  • 빈 배열일 경우 undefined 반환.
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

unshift

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

  • unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 요소가 추가된 배열의 전체 길이를 반환한다.
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

3. splice, slice

  • splice는 배열 자체를 바꾸지만, slice 는 배열 자체는 변경하지 않고, 원하는 부분만 반환한다.

splice

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

  • splice() 메서드는 배열의 기존 요소를 삭제, 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다.
const numbers = [1,2,3,4];

console.log(numbers.splice(1)); // 1번째 인덱스부터 뒷요소 모두 삭제
// [“1”]
console.log(numbers.splice(1, 1)); // 1번째 인덱스부터 1개만 삭제
// [“1”, “3”, “4”]
console.log(numbers.splice(1, 2,5)); // 1번째 인덱스부터 2개 삭제 후 “5” 추가
// [“1”, “5”, “4”];

slice

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

  • slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환한다. 원본 배열은 바꾸지 않는다.
  • slice(begin, end)로, end-1 까지 반환한다.
console.log(numbers.slice()); // 0번째 인덱스부터 모두 반환(전체 복사)
// [“1”, “2”, “3”, “4”]
console.log(numbers.slice(2)); // 2번째 인덱스부터 뒷요소 모두 반환
// [“3”, “4”]
console.log(numbers.slice(1,3)); // 1번째 인덱스부터 2번째 인덱스까지 반환
// [“2”, “3”]

4. split, join

  • split 은 문자열 -> 배열, join 은 배열 -> 문자열

split(String 메서드)

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/split

  • split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.
  • 문자열을 배열로 만들어 반환하는 것이다.
const s = “abcd”;
console.log(s.split()); // [“abcd”]
console.log(s.split(‘’)); // [“a”, ”b”, ”c”, ”d”]

join

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/join

  • join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만든다.
  • join은 배열을 문자열로 만들어 반환하는 것이다.
const arr = [“a”, ”b”, ”c”, ”d”];
console.log(arr.join()); // “a,b,c,d”
console.log(arr.join(‘’)); // “abcd”

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

5. reverse

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

  • 배열 순서를 반전하여, 배열 자체를 바꾸어 반환.
  • 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됨.
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

6. concat

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

  • concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환하는 것. 기존 배열을 변경하지 않는다.
  • 매개변수로 전달된 문자열을 메서드를 호출한 문자열에 붙여 새로운 문자열로 반환한다.
const year =2021;
const month =07;
const day =09;

const result = year.concat(/, month,/, day);
console.log(result); // 2021/07/09
  • 기존 배열 요소를 사용해 새로운 배열을 만들거나, 기존 배열에 요소를 추가한다.
// 예시 1
let arr = [1, 2];
console.log(arr.concat([3, 4])); // [1, 2, 3, 4]
console.log(arr.concat([3, 4], [5, 6, 7])); // [1, 2, 3, 4, 5, 6, 7]
console.log(arr.concat([3, 4], 5, 9, 11)); // [1, 2, 3, 4, 5, 9, 11]

7. indexOf(String, Array 모두 해당)

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

  • 문자열이나 배열에서 주어진 값(요소)과 일치하는 값의 첫 번째 인덱스 반환.
  • 일치하는 값(요소)이 존재하지 않으면 -1 반환.
  • lastIndexOf() 은 끝을 0으로 하여 시작.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

8. includes

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

  • 배열이 특정 요소를 포함하는지 판별하여, 포함 여부에 따라 true/false 반환.
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false
  • includes 는 탐색을 시작할 위치인, 시작 인덱스를 지정할 수 있다.
  • 시작 인덱스가 배열의 길이보다 같거나 크다면, false 를 반환한다.
  • 시작 인덱스가 -1 * array.length 보다 작거나 같다면, 전체 배열이 검색된다.
const arr = ['a', 'b', 'c'];

arr.includes('c', 3);   // false
arr.includes('c', 100); // false
arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
arr.includes('a', -2); // false(-1 * arr.length 인 -3 보다 크므로)

9. sort

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
참고) https://hianna.tistory.com/409 [어제 오늘 내일]

  • sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환한다.
  • 기본 정렬 순서는 문자열의 유니코드 값에 따른다.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
arr.sort((a,b)=>a-b); // 오름차순 정렬
  • sort() 안에 정렬 순서를 정의하는 함수를 넣을 수 있다.
  • 이 함수가 a, b 두개의 element를 파라미터로 입력받는다고 할 때, 함수의 리턴값이 0보다 작을 경우 a가 b보다 앞에 오도록 정렬하고, 0보다 클 경우 b가 a보다 앞에 오도록 정렬한다.
  • 0을 리턴한다면, a와 b의 순서를 변경하지 않는다.

10. reduce

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

  • reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환한다.
  • 설정된 초기값부터 모든 배열을 돌면서 값을 누적하는 것.
  • reduceRight()은 끝에서부터 돈다.
const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
  • 리듀서 함수는 4개의 인자를 가진다.

    누산기 (acc), 현재 값 (cur), 현재 인덱스 (idx), 원본 배열 (src)


11. map

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map

arr.map(callback(currentValue[, index[, array]])[, thisArg])

  • currentValue : 처리할 현재 요소.
    index : 처리할 현재 요소의 인덱스.
    array : map()을 호출한 배열.
    thisArg : callback을 실행할 때 this로 사용되는 값.
  • map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
  • 배열 안의 요소를 원하는 모습으로 바꾸어 반환.

12. filter

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

arr.filter(callback(element[, index[, array]])[, thisArg])

  • element : 처리할 현재 요소.
    index : 처리할 현재 요소의 인덱스.
    array : filter()을 호출한 배열.
    thisArg : callback을 실행할 때 this로 사용되는 값.
  • 조건에 맞는 요소들을 모아 새로운 배열로 반환.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

13. forEach

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])

  • 주어진 배열의 요소 각각에 대해 실행한다.
  • forEach 문 안에서는 continue 를 사용할 수 없다. 대신 return 으로 쓰면 된다.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

2. String 메서드

1. repeat

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

  • string.repeat(count)를 하면 string을 count만큼 반복해서 붙인 새로운 문자열 반환.
'abc'.repeat(-1);   // 범위 에러(반복 횟수는 무한대보다 작아야 하며, 최대 문자열 크기를 넘어선 안됨.)
'abc'.repeat(0);    // ''
'abc'.repeat(1);    // 'abc'
'abc'.repeat(2);    // 'abcabc'
'abc'.repeat(3.5);  // 'abcabcabc' (반복 횟수는 양의 정수여야 함. 정수 단위로 반복함.)
'abc'.repeat(1/0);  // 범위 에러

({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)

2. split

(문자열을 배열로 - Array 메서드에서 설명)


3. indexOf(String, Array 모두 해당)

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

  • 문자열이나 배열에서 주어진 값(요소)과 일치하는 값의 첫 번째 인덱스 반환.
  • 일치하는 값(요소)이 존재하지 않으면 -1 반환.
  • lastIndexOf() 은 끝을 0으로 하여 시작.
const str = "pineapple is sweet";
str.indexOf("apple"); // 4

4. replace

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/replace

  • replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환한다.
  • 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있다.
  • pattern이 문자열 인 경우, 첫 번째 문자열만 치환이 되며 원래 문자열은 변경되지 않는다.
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

5. replaceAll

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

  • 모든 일치 항목이 대체된 새로운 문자열을 반환한다.
  • 원래 문자열은 변경되지 않는다.
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"

// global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

3. 그 외

1. Math.floor

  • 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환.(난수를 정수로!)

2. Math.pow

  • Math.pow(base, exponent)는 base^exponent 반환.
// 제곱한 수를 나타내기
Math.floor(2**5); // 32
Math.pow(2, 5); // 32
profile
좋은 개발자, 좋은 사람

0개의 댓글