TIL - 배열의 메소드 ( 2 )

rain98·2021년 5월 14일
0

TIL

목록 보기
15/32
post-thumbnail

배열의 메소드

array 객체가 갖고 있는 메소드들에 대해 알아보자.
"이 함수들을 전부다 쓴다" 라는것 보다 적어놓고 기억이 날때 보면서 사용하기 위해 기록한다.
잘 이용하면 배열을 보다 효과적으로 사용할 수 있을거같다.

배열의 메소드 (1) : concat(), copyWithin(), entries(), every(), fill(), filter(), find(), findIndex(), forEach(), includes()
url : https://velog.io/@rain98/TIL-%EB%B0%B0%EC%97%B4%EC%9D%98-%EB%A9%94%EC%86%8C%EB%93%9C

배열의 메소드 (2) : indexof(), join(), keys(), lastIndexOf(), map(), pop(), push(), reduce(), reverse()
url : https://velog.io/@rain98/TIL-%EB%B0%B0%EC%97%B4%EC%9D%98-%EB%A9%94%EC%86%8C%EB%93%9C-2

배열의 메소드 (3) : shift(), slice(), some(), sort(), splice(), toString(), unshift()
url : https://velog.io/@rain98/TIL-%EB%B0%B0%EC%97%B4%EC%9D%98-%EB%A9%94%EC%86%8C%EB%93%9C-3


indexOf()

배열에서 지정한 값과 같은 요소의 첫 인덱스를 반환합니다.
없으면 -1을 반환한다.

arr.indexOf(searchElement[, fromIndex])

indexOf() 매개변수

  • searchElement
    배열에서 찾을 요소.

  • fromIndex (선택)
    검색을 시작할 색인이다. 인덱스가 배열의 길이보다 크거나 같은 경우 -1이 반환되므로 배열이 검색되지 않는다. 기본값 : 0

indexOf() 예제

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

요소의 모든 항목 찾기

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

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


join()

배열의 모든 요소를 연결해 하나의 문자열로 만든다.

arr.join([separator])

join() 매개변수

  • separator (선택)
    배열의 각 요소를 구분할 문자열을 지정한다. 이 구분자는 필요한 경우 문자열로 변환된다. 생략하면 배열의 요소들이 쉼표로 구분된다.

join() 예제

const elements = ['Fire', 'Air', 'Water'];

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

console.log(elements.join(''));
// expected output: "FireAirWater"

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

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


keys()

배열의 각 인덱스를 키 값으로 가지는 새로운 객체를 반환한다.

arr.keys()

keys() 예제

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// expected output: 0
// expected output: 1
// expected output: 2

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


lastIndexOf()

지정된 요소가 배열에서 발견될 수 있는 마지막 인덱스를 반환하고, 존재하지 않으면 -1을 반환한다.

arr.lastIndexOf(searchElement[, fromIndex])

lastIndexOf() 매개변수

  • searchElement
    배열에서 찾을 요소.

  • fromIndex (선택)
    역순으로 검색을 시작할 인덱스. 배열의 길이에서 1을 뺀 값(arr.length - 1)이 기본값이므로 지정하지 않을 경우 전체 배열을 검색한다.

lastIndexOf() 예제

var array = [2, 5, 9, 2];
array.lastIndexOf(2);     // 3
array.lastIndexOf(7);     // -1
array.lastIndexOf(2, 3);  // 3
array.lastIndexOf(2, 2);  // 0
array.lastIndexOf(2, -2); // 0
array.lastIndexOf(2, -1); // 3

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


map()

배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출하고, 그 결과를 모아서 만든 새로운 배열을 반환한다.

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

map() 매개변수

  • callback
    새로운 배열 요소를 생성하는 함수. 다음 세 가지 인수를 가집니다.
    • currentValue
      처리할 현재 요소.
    • index (선택)
      처리할 현재 요소의 인덱스.
    • array (선택)
      map()을 호출한 배열.
  • thisArg (선택)
    callback을 실행할 때 this로 사용되는 값.

map() 예제

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

배열에 들어있는 숫자들의 제곱근을 구하여 새로운 배열을 만들기

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots는 [1, 2, 3]
// numbers는 그대로 [1, 4, 9]

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


pop()

배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

arr.pop()

pop() 예제

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"]

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


push()

배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.

arr.push(element1[, ...[, elementN]])

push() 매개변수

  • elementN
    배열의 끝에 추가할 요소.

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"]

배열에 엘리먼트를 추가 하기
다음 코드는 두가지 엘리먼트를 포함하는 스포츠 배열을 생성하고 두개의 엘리먼트를 추가 한다. total 변수는 추가한 배열의 새 길이 값을 포함한다.


var sports = ['축구', '야구'];
var total = sports.push('미식축구', '수영');

console.log(sports); // ['축구', '야구', '미식축구', '수영']
console.log(total);  // 4

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


reduce()

배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환한다.

arr.reduce(callback[, initialValue])

reduce() 매개변수

  • callback
    배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받는다.
    • accumulator
      누산기는 콜백의 반환값을 누적한다.
    • currentValue
      처리할 현재 요소.
    • currentIndex (선택)
      처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작한다.
    • array (선택)
      reduce()를 호출한 배열.
  • initialValue (선택)
    callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용한다. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생한다.

reduce() 예제

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + 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

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


reverse()

배열의 요소 순서를 반전시킨다.

a.reverse()

reverse() 예제

const arr = [1, 2, 3];
console.log(arr); // [1, 2, 3]

arr.reverse();
console.log(arr); // [3, 2, 1]

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

profile
헷갈리거나 기억에 남기고 싶은것을 기록합니다.

0개의 댓글