JS에서 Array가 가지고 있는 메소드들

머리가 나쁘면 머리가 고생한다

Posted by surin01 on July 09, 2021 · 5 mins read

Array가 가지고 있는 메소드들 정리

push

const arr = ["aa", "bb", "cc"];
const count = arr.push("dd");
console.log(arr) // [aa, bb, cc, dd]
console.log(count) // 4

concat

const arr1 = ["aa", "bb", "cc"];
const arr2 = ["cc", "dd", "ee"];
const arr3 = arr1.concat(arr2);

cosole.log(arr3); // ["aa", "bb", "cc", "cc", "dd", "ee"];

copyWithin

const arr1 = ["aa", "bb", "cc", "dd", "ee", "ff"];
console.log(arr1.copyWithin(0, 2, 4));
// copy array index 2 to before index 4 => ["cc", "dd"]
// paste copied array to index 0 => ["cc", "dd", "cc", "dd", "ee", "ff"]
// expected output: ["cc", "dd", "cc", "dd", "ee", "ff"]

const arr2 = ["aa", "bb", "cc", "dd", "ee", "ff"];
console.log(arr2.copyWithin(0, 3))
// copy array index 3 to end => ["dd", "ee", "ff"]
// paste copied array to index 0 => ["dd", "ee", "ff", "dd", "ee", "ff"]
// expected output: ["dd", "ee", "ff", "dd", "ee", "ff"]

entries

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

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

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

fill

const array1 = [1, 2, 3, 4];
//0으로 index 2부터 4까지 채우기
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// 5로 인덱스 1부터 끝까지 채우기
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

// 전체를 6으로 채우기
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

// 객체를 할당시 객체 참조
let arr = Array(3).fill({});
arr[0].test = "testString";
// => [{test:"testString"},{test:"testString"},{test:"testString"}]

filter

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

find

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

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

findIndex

const array1 = [5, 12, 8, 130, 44];

console.log(array1.findIndex((element) => element > 13));
// expected output: 3

##


##


##