JS/드림코딩앨리

8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리

배워도끝이없네 2021. 4. 21. 10:35
//object와 array의 차이점
//object는 서로 연관된 특징과 행동들을 묶어놓는것 (토끼,사람,당근..같은 범주)
//이러한 object들을 같은종류로 묶어놓은것을 자료구조라고 한다.
//type이 있는 데이터는 동일한 타입만 묶을 수 있다.\


//Array > 

//1. Declaration
const arr1 = new Array();
const arr2 = [1,2]; //배열을 만드는법은 new를 선언하거나 이렇게 만든다.


//2. Index position <<배열은 인덱스를 활용하는게 중요하다
const fruits = ["사과","바나나"];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);

console.clear();
//3. Looping over an array
// print all fruits
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 배열의 index만큼 반복하면서 인자를 꺼냄
fruits.forEach((fruit)=> console.log(fruit));

//4. Addition, deletion , copy
// push : add an item to the end
fruits.push('딸기','딱숭아');
console.log(fruits);

// pop : remove an item from the end
fruits.pop();
console.log(fruits);

// unshift : add an item to the beginning 앞에서부터 데이터를 넣기
fruits.unshift('배너나','땔기');
console.log(fruits);

//shift : remove an item from the beginning
fruits.shift();
console.log(fruits);

//note!! shift, unshift는 아주아주 속도가 느리다
//splice : 지정된 포지션에서 item을 삭제하는것
fruits.push('기딸기','물복','레먼');
console.log(fruits);
fruits.splice(1,3,'사과','수박');
console.log(fruits); //몇개지울지 말하지 않으면 시작인덱스부터 다지움

//combine two arrays 2개의 배열을 합치는것
const fruits2 = ['모과','버섯'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

//5. Searching
// 인덱스를 찾을때
console.clear();
console.log(fruits);
console.log(fruits.indexOf('사과'));
console.log(fruits.indexOf('수박'));
console.log(fruits.includes('코코넷'));

//lastIndexOf
console.clear();
fruits.push('사과');
console.log(fruits.indexOf('사과')); //indexof는 앞에서부터 제일 먼저나온 값에 대한 인덱스를 나타냄
console.log(fruits.lastIndexOf('사과')); //lastIndexof는 뒤에서부터 제일 먼저나온 값에 대한 인덱스를 나타냄


​