Javascript 배열 기초(2)

JongIk Park·2021년 6월 20일
0

javascript

목록 보기
2/21
post-thumbnail

JavaScript의 Array 관련 함수

이전 글과 겹치는 부분이 있지만 복습한다는 생각으로 다시 한번 정리

Array.from()

  • 문자열이나 배열의 요소들을 리턴할 때 쓴다.
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

console.log(Array.from({ a: '1', b: '2' }));
// [] : object는 빈 배열로 리턴된다.

let obj = { a: '1', b: '2' };
Array.from(Object.keys(obj)); // key값 리턴
// ["a", "b"]
Array.from(Object.values(obj)); // value값 리턴
// ["1", "2"]

Array.of()

  • Array.of() 요소들을 배열로 반환, Array()는 요소들로 새로운 배열을 생성하는 듯
Array.of(7);       // [7] 
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]

Array(7);          // [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]

Array.prototype.concat()

  • 두 개의 배열을 연결한다 (합친다)
  • 기존배열을 변경하지 않는다. 추가된 새로운 배열을 반환하며 중첩 배열 내부로 재귀하지 않는다.
const alpha = ['a', 'b', 'c'];
const numeric = [1, 2, 3];

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

let b = [1, 2, 3];
let c = [4, 5, [6, 7]];
b.concat(c);
// [1, 2, 3, 4, 5, [6, 7]]

Array.prototype.fill()

  • 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채운다.
  • Array.fill(value,start,end);
var 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]

Array.prototype.filter()

  • 주어진 함수의 조건을 통과하는 모든 요소들을 모아 새로운 배열로 반환
  • 기존의 배열은 변경되지 않는다.
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

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

console.log(words);
console.log(result);
// Array ["spray", "limit", "elite", "exuberant", "destruction", "present"]
// Array ["exuberant", "destruction", "present"]

Array.prototype.find()

  • 주어진 함수의 조건을 만족하는 첫 번째 요소의 값을 반환한다.
  • 해당 요소가 없다면 undefined를 반환한다.
var array1 = [5, 12, 8, 130, 44];
var found = array1.find(function(element) {
    return element > 10;
});

console.log(found);
// expected output: 12

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

const result = inventory.find(fruit => fruit.name === 'cherries');

console.log(result) // { name: 'cherries', quantity: 5 }

Array.prototype.forEach()

  • 주어진 함수를 배열 요소 각각에 대해 실행한다.
  • forEach()는 배열을 변형하지 않지만, callback이 변형할 수 있다.
  • 예외를 던지지 않고는 중간에 forEach()를 멈출 수 없다.

Array.prototype.includes()

  • 배열이 특정 요소를 포함하고 있는지를 판단한다.
  • arr.includes(valueToFind, fromIndex);
  • 객체는 확인 불가능하다.
// array length is 3
// fromIndex is -1
// computed index is 3 + (-1) = 2

var arr = ['a', 'b', 'c'];

arr.includes('a', -1); // false
arr.includes('a', -2); // false
arr.includes('a', -3); // true

var ary = [
    { a: 'a', b: 'b'},
    { a: 'aa', b: 'bb'}
];
ary.includes({ a: 'a', b: 'b'}); // false. 객체는 확인 불가

Array.prototype.keys()

keys() 메서드는 배열의 각 인덱스를 키 값으로 가지는 새로운 Array Iterator 객체를 반환한다.

Array.prototype.map()

  • 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
  • map이 처리할 요소의 범위는 첫 callback을 호출하기 전에 정해진다.
    map이 시작한 이후 배열에 추가되는 요소들은 callback을 호출하지 않는다.
var 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]
console.log(array1); // Array [1, 4, 9, 16] 원본 유지

// 아래 라인을 보시면...
['1', '2', '3'].map(parseInt);
// 결과를 [1, 2, 3] 으로 기대할 수 있습니다.
// 그러나 실제 결과는 [1, NaN, NaN] 입니다.

// parseInt 함수는 보통 하나의 인자만 사용하지만, 두 개를 받을 수 있습니다.
// 첫 번째 인자는 변환하고자 하는 표현이고 두 번째는 숫자로 변환할 때 사용할 진법입니다.
// Array.prototype.map은 콜백에 세 가지 인자를 전달합니다.
// 배열의 값, 값의 인덱스, 그리고 배열
// 세 번째 인자는 parseInt가 무시하지만 두 번째 인자는 아닙니다.

Array.prototype.reduce()

  • 배열의 각 요소에 대해 주어진 reducer 함수를 실행하고, 하나의 결과값을 반환한다.
  • 배열의 모든 값을 합산한다.
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
    return accumulator + currentValue;
});

Array.prototype.shift()

  • shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환한다.
  • 이 메서드는 배열의 길이를 변하게 한다.

Array.prototype.slice()

  • 배열의 begin부터 end까지 (end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환한다.
  • 원본 배열은 수정되지 않는다.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
const ary1 = animals.slice(2);
const ary2 = animals.slice(2, 4)

console.log(animals);
console.log(ary1);
console.log(ary2);

animals[0] = 'aaaaa';
console.log(animals);
console.log(ary1);

// Array ["ant", "bison", "camel", "duck", "elephant"]
// Array ["camel", "duck", "elephant"]
// Array ["camel", "duck"]
// Array ["aaaaa", "bison", "camel", "duck", "elephant"]
// Array ["camel", "duck", "elephant"]

Array.prototype.sort()

  • 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환한다.
  • 기본 정렬 순서는 문자열의 유니코드 코드포인트를 따른다 (오름차순)

Array.prototype.splice()

  • 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다.
  • 제거할 요소의 수와 추가할 요소의 수가 다른 경우 배열의 길이는 달라진다.
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']

months.splice(1, 2, 'May');
console.log(months);
// expected output: Array ["Jan", "May", "April", "May"]

Array.prototype.toString()

  • 지정된 배열 및 그 요소를 나타내는 문자열을 반환한다.
var array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

Array.prototype.unshift()

  • 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환한다.
var array1 = [1, 2, 3];

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

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


var arr = [1, 2];

arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

참고글📌 : https://geniee.tistory.com/21?category=848930

profile
신입 프론트엔드 개발자

0개의 댓글