TIL - 배열의 메소드( 1 )

rain98·2021년 5월 14일
0

TIL

목록 보기
14/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


concat()

인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환한다.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

concat() 예제

배열 세 개 이어붙이기

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

num1.concat(num2, num3);
// 결과: [1, 2, 3, 4, 5, 6, 7, 8, 9]

배열에 값 이어붙이기

const alpha = ['a', 'b', 'c'];
alpha.concat(1, [2, 3]);
// 결과: ['a', 'b', 'c', 1, 2, 3]

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


copyWithin()

배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환한다.

arr.copyWithin(target[, start[, end]])

copyWithin() 매개변수

  • target
    복사한 값을 넣을 위치를 가리키는 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산한다.

  • start (선택사항)
    복사를 시작할 위치를 가리키는 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
    기본값은 0으로, start를 지정하지 않으면 배열의 처음부터 복사합니다.

  • end (선택사항)
    복사를 끝낼 위치를 가리키는 인덱스. copyWithin은 end 인덱스 이전까지 복사하므로 end 인덱스가 가리키는 요소는 제외합니다. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
    기본값은 arr.length로, end를 지정하지 않으면 배열의 끝까지 복사합니다.

copyWithin() 예제

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

console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]
//3번 index인 'd'복사후 0번 자리에 덮어쓰기

console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
//3번 index에서 4번 index 까지 'd','e' 복사후 1번 자리에 덮어쓰기

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


entries()

배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 배열 반복자 객체를 반환합니다.

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]

entries() 예제

인덱스와 요소 이터레이팅

const a = ['a', 'b', 'c'];

for (const [index, element] of a.entries())
  console.log(index, element);

// 0 'a'
// 1 'b'
// 2 'c'

for…of 루프 사용

var a = ['a', 'b', 'c'];
var iterator = a.entries();

for (let e of iterator) {
  console.log(e);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']

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


every()

배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트한다.
만약 배열의 모든 요소가 제공된 판별 함수를 통과하면 true를 반환한다.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

every 예제

모든 배열 요소의 크기 테스트
다음 예는 배열의 모든 요소가 10보다 더 큰지 테스트한다.

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

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


fill()

배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채운다.

arr.fill(value[, start[, end]])

fill() 매개변수

  • value
    배열을 채울 값.
  • start (선택)
    시작 인덱스, 기본 값은 0.
  • end (선택)
    끝 인덱스, 기본 값은 length.

fill() 예제

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

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

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


filter()

인자로 주어진 함수로 배열내의 모든 요소를 테스트해서 참인 요소만으로 만들어진 배열을 반환한다.

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

filter() 매개변수

  • callback
    각 요소를 시험할 함수. true를 반환하면 요소를 유지하고, false를 반환하면 버린다. 다음 세 가지 매개변수를 받는다.
  • element
    처리할 현재 요소.
    • index (선택)
      처리할 현재 요소의 인덱스.
    • array (선택)
      filter를 호출한 배열.
  • thisArg (선택)
    callback을 실행할 때 this로 사용하는 값.

filter() 예제

모든 작은 값 걸러내기
다음 예는 값이 10 이하인 모든 요소가 제거된 걸러진 배열을 만들기 위해 filter()를 사용한다.

function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered 는 [12, 130, 44]

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


find()

주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환한다.
만약 조건에 해당하는 요소가 없다면 undefined를 반환한다.

arr.find(callback[, thisArg])

find() 매개변수

  • callback
    배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받는다.
    • element
      콜백함수에서 처리할 현재 요소.
    • index (선택)
      콜백함수에서 처리할 현재 요소의 인덱스.
    • array (선택)
      find 함수를 호출한 배열.
  • thisArg (선택)
    선택 항목. 콜백이 호출될 때 this로 사용할 객체.

find() 예제

속성 중 하나를 사용하여 배열에서 객체 찾기

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 }

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


findIndex()

주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합한다.
만족하는 요소가 없으면 -1을 반환한다.

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

findIndex() 매개변수

  • callback
    3개의 인수를 취하여 배열의 각 값에 대해 실행할 함수.
    • element
      배열에서 처리중인 현재 요소.
    • index
      배열에서 처리중인 현재 요소의 인덱스.
    • array
      findIndex 함수가 호출된 배열.
  • thisArg (선택)
    선택 사항. 콜백을 실행할 때 this로 사용할 객체.

findIndex() 예제

배열에서 소수의 색인 찾기

다음 예제에서는 배열에서 소수 (소수가없는 경우 -1을 반환) 인 요소의 인덱스를 찾는다.

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2

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


🔥forEach()

배열내의 모든 요소에 대해 인자로 주어진 함수를 실행한다.

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

forEach() 매개변수

  • callback
    각 요소에 대해 실행할 함수. 다음 세 가지 매개변수를 받는다.
    • currentValue
      처리할 현재 요소.
    • index (선택)
      처리할 현재 요소의 인덱스.
    • array (선택)
      forEach()를 호출한 배열.
  • thisArg (선택)
    callback을 실행할 때 this로 사용할 값.

forEach() 예제

초기화하지 않은 값의 반복 생략

const arraySparse = [1,3,7]
let numCallbackRuns = 0

arraySparse.forEach(function(element){
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3

for 반복문을 forEach()로 바꾸기

const items = ['item1', 'item2', 'item3'];
const copy = [];

// 이전
for (let i=0; i<items.length; i++) {
  copy.push(items[i]);
}

// 이후
items.forEach(function(item){
  copy.push(item);
});

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


includes()

배열에 특정 요소가 포함돼있는지 알아내어 true 또는 false를 반환한다.

arr.includes(valueToFind[, fromIndex])

includes() 매개변수

⚠️ 참고: 문자나 문자열을 비교할 때, includes()는 대소문자를 구분한다.

  • valueToFind
    탐색할 요소.

  • fromIndex (선택)
    이 배열에서 검색을 시작할 위치다. 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색한다. 기본값은 0

includes() 예제

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

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


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

0개의 댓글