자바스크립트 6: Array

수정·2022년 6월 12일
0

1

목록 보기
10/12
post-thumbnail

오브젝트: 토끼와 당근
토끼: 동물/먹는다/뛴다/귀 두개
당근: 채소/주황색/비타민c
자료구조: 동일한 타입의 오브젝트를 담는 바구니

Array

1. Declaration

const arr1 = new Array();
const arr2 = [1, 2];

2. Index pocition

const fruits = ['🍎, '🍌'];
console.log(fruits);
console.log(fruits.length)
console.log(fruits[0]);
=🍎
console.log(fruits[1]);
=🍌
console.log(fruits[fruits.length - 1]); 
// 총 길이에 -1를 하면 마지막 인덱스를 받아온다. (0부터 시작)

3. Looping over an array
: print all fruits

a. for 
for (let i= 0; i < fruits.length; i++) {
    console.log(fruits[i]);
    
}

b. for of
for (let fruit of fruits) {
    console.log(fruit);
}

c. forEach
fruits.forEach((fruit) => console.log(fruit));
// 배열 안에 들어있는 벨류들마다 함수를 출력한다.

4. Addtion, deletion, copy

pop: remove an item from the end
fruits.pop(); // 한 줄 입력할 때마다 끝에서 하나씩 사라진다.
fruits.pop(); // 이렇게 한 줄 더 적으면 하나 더 사라진다.

unshift: add an item to tje benigging
fruits.unshift('🍐','🍈')
// 앞에서부터 추가가 된다.

shift: remove an item from the benigging
fruits.shift(); // 앞에서부터 사라진다.

note!! shift, unshift are slower than pop, push

splice: remove an item by index position
fruits.push('🍐', '🍒' ,'🍈');
fruits.splice(1(인덱스), 1(몇 개 지울 건지)); 
//지정한 인덱스부터 모든 데이터를 지우기 때문에 시작하는 인덱스와 함께 몇 개를 지울지 정해야 한다.
fruits.splice(1, 1, '🍍', '🫐')
//첫 번째 인덱스와 그 다음 인덱스를 지운 뒤, 두 가지 과일을 추가한다. 는 뜻

combine two arrays
const fruits2 = ['🥥', '🥝']
const newFruits fruits.concat(fruits2);
// fruit2가 추가되어 최종적으로 총 7개의 과일이 나온다.

5. Searching
: find the index

indexOf
// indexOf를 사용하면 몇 번째 사과가 있는지 알려준다.
console.log(fruits.indexOf('🍎'));
=0
console.log(fruits.indexOf('🥒');
=-1 
//인덱스가 배열 안에 없으므로 값은 -1이 된다.

includes
console.log(fruits.includes('🥭'));
=false
//배열안에 있는지 없는지 true or false로 답한다.

lastIndexOf
console.log(fruits.lastIndexOf('🍎'));
똑같은 인덱스를 추가했을 경우 last index는 뒤에 있는
추가된 인덱스의 순서를 알려준다.

출처: 드림코딩 자바스크립트 기초 강의 (ES5+)

0개의 댓글