TIL 19 | Array APIs

Saemsol Yoo·2020년 12월 22일
0

javascript

목록 보기
10/25
post-thumbnail

length

배열의 길이를 숫자로 반환한다.

const array = ['1️⃣','2️⃣','3️⃣'];
console.log(array.length); 	// 3



toString()

배열을 string 으로 반환 한다.
→ 각 배열의 item들이 comma, 로 이어져서 string(문자열)이 된다.

const array1 = [1, 2, 'a', '1a'];

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



toLocaleString()

배열의 요소를 string 으로 반환 하면서, 고유한 문자열 을 함께 반환한다.
ex) 세자리 컴마, 날짜표시 / 등

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
//'1,a,12/21/1997, 2:12:00 PM'

const localeString = array1.toLocaleString('kr', { timeZone: 'UTC' });
//'1,a,1997. 12. 21. 오후 2:12:00'

const array2 = [1994, 1981];
console.log(array2.toLocaleString());
//'1,994,1,981'



pop()

배열에서 마지막 요소를 제거하고 그 요소를 반환한다.
→ 호출된 배열이 변화하며, pop으로 제거된 요소도 return으로 받을 수 있다.

const array = ['1️⃣','2️⃣','3️⃣'];
const popArray = array.pop();

console.log(array); //[ '1️⃣', '2️⃣' ]   기존 배열에서 마지막 요소 하나가 삭제됐다.
console.log(popArray); //'3️⃣'          제거된 요소가 반환되어 popArray에 할당되었다.



push()

배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.
→ 호출된 배열도 변화하고, 추가되어 바뀐 배열의 길이를 받을 수 있다.

const array = ['1️⃣','2️⃣','3️⃣'];
const pushArray = array.push('4️⃣','5️⃣');

console.log(array); //[ '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣' ]  기존 배열 뒤에 새롭게 요소들이 추가되었다.
console.log(pushArray); //5                           배열의 새로운 길이가 반환되어 할당되었다.



concat()

인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환한다.
→ 기존 배열에는 변화가 생기지 않는다.

const first = ["one","two","three"];
const second = ["four","five","six"];
const third = ["seven","eight","nine"];

const combined = first.concat(second,third);

console.log(combined);
// [ 'one',   'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ]

console.log(first); //[ 'one', 'two', 'three' ]



join()

배열의 모든 요소를 연결해 하나의 문자열 로 만든다.
→ seperator를 string타입으로 넣어주면, 이 구분자를 넣어줘서 stirng을 만들어준다.
→ seperator를 넣어주지 않으면, 그냥 comma로 이어준다.
→ return값은 string 이다.

join ( separator?:string )

const fruits = ['apple', 'banana', 'orange'];

console.log(fruits.join());            //'apple,banana,orange'
console.log(fruits.join(' and '));     //'apple and banana and orange'



reverse()

배열의 순서를 뒤집는다.
→ 첫 번째 요소는 마지막 요소가 되고 마지막 요소는 첫 번째 요소가 된다.
→ 순서가 바뀐 배열을 반환된다.
→ 기존 함수도 순서가 바뀐다.

const array = [1, 2, 3, 4, 5];
const reversedArray = array.reverse();
  
console.log(reversedArray); //[ 5, 4, 3, 2, 1 ]    순서가 바뀐 배열이 반환되어 할당되었다.
console.log(array); //[ 5, 4, 3, 2, 1 ]            기존 배열 자체도 순서가 바뀌어버린다.



shift()

배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환한다.
pop( ) 은 마지막 요소를 제거하는 거였다!

const array = ['1️⃣','2️⃣','3️⃣'];
const shiftArray = array.shift();

console.log(array); //[ '2️⃣', '3️⃣' ]     기존 배열에서 첫번째 요소 하나가 삭제됐다.
console.log(shiftArray); //'1️⃣'          제거된 요소가 반환되어 할당되었다.



unshift()

새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환한다.
push( ) 는 마지막에 요소를 추가하는 거였다!

const array = ['1️⃣','2️⃣','3️⃣'];
const unshiftArray = array.unshift('🆕','💛');

console.log(array); //[ '🆕', '💛', '1️⃣', '2️⃣', '3️⃣' ]  기존 배열 앞에 새로운 요소들이 추가되었다.
console.log(unshiftArray); //5                         배열의 새로운 길이가 반환되어 할당되었다.



splice()

배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다.

splice ( 시작하는 index, 몇개나 지울지, 원하는 데이터를 더 추가 )
→ 기존배열이 변경된다.

const array = ['1️⃣','2️⃣','3️⃣','4️⃣','5️⃣'];
const spliceArray = array.splice(1,2,'✅');
//1번 index부터 2개가 삭제되고, 삭제된 2와 3이 반환되어 할당된다.

console.log(spliceArray); //[ '2️⃣', '3️⃣' ]
console.log(array);  //[ '1️⃣', '✅', '4️⃣', '5️⃣' ]
//기존배열에서 1번 index부터 2개가 삭제되고, 그자리에 ✅ 추가되어 변경됐다. 



slice()

어떤 배열의 begin부터 end까지(end 미포함)에 대한 복사본을 새로운 배열 객체로 반환한다.
→ 기존배열은 변경되지 않는다.

slice ( start index, end index(미포함) )

const array = ['1️⃣','2️⃣','3️⃣','4️⃣','5️⃣'];
const sliceArray = array.slice(1,3);
//1번 index부터 2번 index까지 (3번 index는 미포함) 복사본이 반환되어 할당된다.

console.log(sliceArray);   //[ '2️⃣', '3️⃣' ]
console.log(array);        //[ '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣' ]
//기존배열은 변경되지 않는다.



sort()

배열 요소의 순서를 새로 정렬해준다.
→ 만약 compareFunction을 전달해주지 않는다면, 영어는 알파벳 순서로 정렬이 되고,
숫자는 첫번째 숫자를 기준으로 정렬이 된다.
→ 기존 배열도 정렬되어 바뀐다.

const scores = ['35','94','17','40','81'];
const sortScores = scores.sort((a,b) => a - b);
//a-b로 했을땐 작은거부터 큰 순서로 정렬된다.

console.log(sortScores);  //[ '17', '35', '40', '81', '94' ]
console.log(scores);      //[ '17', '35', '40', '81', '94' ]
//기존배열도 순서가 바뀐다.


const sortScores2= scores.sort((a,b) => b - a);
//b-a로 했을 땐 큰거에서 작은 순서로 정렬된다.

console.log(sortScores2); //[ '94', '81', '40', '35', '17' ]
console.log(scores);      //[ '94', '81', '40', '35', '17' ]
//기존배열도 순서도 또 바뀐다.



indexOf()

배열에서 지정된 요소를 찾아 첫 번째로 발견한 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
→ fromIndex는 써줘도 되고, 안써줘도 된다. 생략되면 index0부터 찾는다.

indexOf ( searchElement, fromIndex? )

const hearts = ['💗','🧡','💛','💚','💜','💗','💚'];
console.log(hearts.indexOf('💚')); //3        index0부터 찾으면 3번 index 하트를 찾고,
console.log(hearts.indexOf('💚',5)); //6      index5부터 찾으면 6번 index 하트를 찾는다.



lastIndexOf()

배열에서 지정된 요소를 찾아 뒤에서부터 첫 번째로 발견한 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
→ fromIndex는 써줘도 되고, 안써줘도 된다. 생략되면 제일 마지막 인덱스부터 거슬러 올라와 찾는다.

const hearts = ['💗','🧡','💛','💚','💜','💗','💚'];
console.log(hearts.lastIndexOf('💚')); //6       마지막 index부터 찾기 때문에  6번index 하트를 찾고,
console.log(hearts.lastIndexOf('💚',5));//3      index5부터 찾으면 3번 index 하트를 찾는다.



every()

배열 안의 모든 요소전달된 콜백함수를 충족하는지 테스트한다.
→ 모든 요소들이 callback을 충족해야만 true가 반환된다.

const scores = [45, 77, 98, 56, 23, 13];

console.log(scores.every((score)=> score > 50));  //false   
//50점 이하인 요소들이 있기 때문에 false가 반환된다. 

console.log(scores.every((score)=> score > 10));  //true    
//모든요소가 10점 이상에 충족하기 때문에  true가 return 된다.



some()

배열 안의 하나의 요소 라도 전달된 콜백함수를 충족하는지 테스트한다.
→ 하나의 요소라도 콜백함수 조건에 만족한다면 true가 반환된다.

const scores = [45, 77, 98, 56, 23, 13];

console.log(scores.some((score)=> score > 50));  //true   
//50점 이하인 요소가 하나 이상 있기때문에 true가 반환된다.
profile
Becoming a front-end developer 🌱

0개의 댓글

관련 채용 정보