Node.js

[JavaScript] Array.prototype 함수정의 1

J 코딩 2022. 5. 9. 01:10
반응형

Array.prototype.[method]

1. at()

정수 값을 받아, 배열에서 해당 값에 해당하는 인덱스의 요소를 반환합니다. 양수와 음수 모두 지정할 수 있고, 음수 값의 경우 배열의 뒤에서부터 인덱스를 셉니다

 

[using]

 

const arr = [1, 2, 3, 4, 5];

let idx = 3;

console.log(`The result is ${idx}, ${arr.at(idx)}`);

 

[result]

3, 4

 

첫번째 결과값(${idx})은 idx에 할당된 값 3을 나타내며 두번째 결과값(${arr.at(idx)})은 배열의 3번째 값인 4를 나타낸다.

 

 

2. concat()

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

 

[using]

 

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
const result = arr1.concat(arr2);

console.log(result);

 

[result]

["a", "b", "c", "d", "e", "f"]

 

처음 선언한 배열 arr1의 값 a, b, c에 arr2의 값을 더한다. (단순히 문자열로서 뒤에 합해진다)

이때 해당 결과값을 새로운 변수에 담아야 값이 합해진다.

 

 

3. copyWithin()

배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환합니다. 이 때, 크기(배열의 길이)를 수정하지 않고 반환합니다

 

[using]

 

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

console.log(arr.copyWithin(0, 1, 4));
console.log(arr.copyWithin(1, 4));

 

[result]

["b", "c", "d", "d", "e"]

["b", "e", "d", "d", "e"]

 

Array.prototype.copyWithin(target, start, end)

해당 메서드는 사용 즉시 배열에 반영된다. 첫번째 매개변수는 변경 할 타겟의 위치를 나타내며 두번째 매개변수는 복사할 시작, 세번째 매개변수는 복사할 마지막을 뜻한다.

 

 

4. entries()

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

 

[using]

 

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

const iterator = arr.entries();

for(var i = 0; i < arr.length; i++)
    console.log(iterator.next().value);

 

[result]

Array[0, "a"]

Array[1, "b"]

Array[2, "c"]

 

배열의 key, value를 동시에 반환 할 수 있다.

 

 

5. every()

배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다. Boolean 값을 반환합니다

 

[using]

 

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

const arr1 = [1, 30, 39, 29, 10, 13];
const arr2 = [2, 5, 34, 12, 35, 56];

console.log(arr1.every(isBelowThreshold));
console.log(arr2.every(isBelowThreshold));

 

[result]

true

false

 

해당 배열안의 모든 값이 정한 조건에 맞는지 판별한다. (맞으면 true, 아니면 false)

반응형