[JavaScript] 배열의 Method

Hannahhh·2022년 7월 10일
0

JavaScript

목록 보기
10/47

👀 배열의 Method


✔ Array.isArray()

: 특정 값이 배열인지 아닌 지 판별한다.

let words = ['사과', '배', '오렌지'];

Array.isArray('문자열'); // false
Array.isArray(123);     // false
Array.isArray(words);   // true
Array.isArray([1,2,3]); // true
Array.isArray([]);      // true

✔ indexOf(), includes()

: 특정 값이 배열에 포함되어 있는 지 확인한다.(대소문자 구분)

indexOf의 경우, index 정보까지 얻어낼 수 있지만, includes는 존재 여부만 알 수 있기때문에 범용성 측면에서 indexOf가 더 유용하다.
또한, includes는 internet explorer에서 작동되지 않는다. 따라서, 호환성 측면에서도 indexOf가 유용하다.

let words = ['Radagast', 'the', 'Brown'];

//특정한 element를 찾는다.
words.indexOf('the')      // 1
words.indexOf('Brown')    // 2
words.indexOf('Radagast') // 0
words.indexOf('없는단어')  // -1


//존재여부를 파악한다.
words.indexOf('Brown') !== -1   // true
words.indexOf('없는단어') !== -1 // false

//위의 코드를 함수로 나타내어 결과를 return
//hasElement(배열, 찾으려는엘리먼트) return true or false
function hasElement(arr, element){
  let isPresent = arr.indexOf(element) !== -1;
  return isPresent;
}

hasElement(words, 'Brown') // true
hasElement(words, '없는것') // false

//includes: search element
words.includes('Brown')
words.includes('없는것')

👀 Mutable Method

원본 배열을 직접 변경한다.


✔ push(), pop(), shift(), unshift()

: 배열의 요소를 추가 및 삭제한다.

let arr = ['pine', 'apple'];
console.table(arr)  // 테이블화 되어서 나타나기 때문에 index와 value를 보기 좋음!

arr.push('yellow') // 3  2번째 index에 'yellow' 추가

arr.pop()         // 'yellow'    2번째 index 삭제 

// 앞 쪽의 인덱스를 추가, 삭제 하려면?
arr.shift()       // 'pine'      0번째 index 삭제 

arr.unshift('pine') // 'pine'    0번째 index 추가

✔ splice()

:배열의 요소를 추가 및 삭제할 때 범용적으로 사용된다. slice와 달리 호출 대상을 바로 수정한다.

splice(시작 index, 삭제할 요소의 개수, 추가될 요소)
2번째 parameter를 지정하지 않을 시, 배열의 마지막 요소까지 삭제한다.
추가될 요소는 3,4,5...번째 parameter로 계속 줄 수 있다.

삭제한 배열을 반환하며, 삭제된 요소가 없을 시 빈 배열을 반환한다.

const a = [1,2,3,4,5];
a.splice(4);                // [5], a=[1,2,3,4]
a.splice(1,2);              // [2,3], a=[1,4]
a.splice(1,1);              // [4], a=[1]
a.splice(0,0,6);            // [], a=[6,1]
a.splice(2,0,"5");          // [], a=[6,1,'5']
a.splice(1,1,'2','3','4');  // [1], a=[6,'2','3','4','5']

✔ reverse()

:배열 요소의 순서를 전부 반대로 교체한다.

const arr = [1, true, "JavaScript", "자바스크립트"];

arr.reverse(); // [자바스크립트,JavaScript,true,1]]

✔ sort()

: 배열의 요소들을 알파벳 순서에 따라 정렬한다.

var strArr = ["로마", "나라", "감자", "다람쥐"]; // 한글은 ㄱ,ㄴ,ㄷ순으로 정렬됨.

var numArr = [10, 21, 1, 2, 3];                  // 숫자는 각 자릿수 별로 비교된 후 정렬됨.

strArr.sort(); // [감자,나라,다람쥐,로마]

numArr.sort(); // [1,10,2,21,3]

👀 Immutable Method

원본 배열을 변경하지 않고, 새로운 배열을 생성하여 반환한다.


✔ split()

: 문자열을 배열로 변환한다.(string method)

const color = 'red, blue, green';

let a = color.split(',');
console.log(a); // ['red','blue','green']

a = color.split(',',2); //limit 2
console.log(a); // ['red','blue']

a = color.split(); //구분자 x
console.log(a); // ['red, blue, green']

✔ join()

: 배열을 문자열로 변환한다.

const color = ['red','blue','green'];

let a = color.join(); //구분자 x, default 콤마(,)
console.log(a); // red,blue,green

a = color.join(''); 
console.log(a); // redbluegreen

a = color.join(' ');
console.log(a); // red blue green

a = color.join(' and ');
console.log(a); // red and blue and green

링크텍스트


✔ slice()

: 특정 범위를 복사한 값을 담고 있는 새로운 배열을 생성한다.(부분배열 반환) 따라서, 원본은 수정되지 않는다.

slice(시작 index, 종료 index)
시작 index ~ 종료 index 전의 index까지 반환하며, 종료 index 지정하지 않을 시, 시작 index부터 마지막 요소까지 반환한다.

const a = [1,2,3,4,5];
a.slice(0,4);     // [1,2,3,4]
a.slice(3);       // [4,5]
a.slice(1, -1);   // [2,3,4]
a.slice(-3, -2);  // [3]

링크텍스트


✔ toString()

:배열의 요소들을 문자열로 변환하고 쉼표로 분리한 list를 반환한다.

const a = [1,2,3,4,5];
a.toString();     // '1,2,3,4,5'

✔ concat()

: 배열의 뒤에 argument로 전달받은 배열을 합쳐서 만든 새로운 배열을 반환한다.

const arr = [1, true, "JavaScript"];

arr.concat([2, false, "문자열"]); // [1,true,JavaScript,2,false,문자열]
arr.concat([2], [3, 4]);          // [1,true,JavaScript,2,3,4] -> 2개 이상의 배열도 한 번에 합칠 수 있음.
arr.concat("다섯", [6, 7]);       // [1,true,JavaScript,다섯,6,7] -> 값과 배열도 한 번에 합칠 수 있음.



Reference: 코드스테이츠, TCP School
링크텍스트

0개의 댓글