배열 array
1. 배열 선언
const arr1=new Array();
const arr1=[1,2];
배열을 new로 선언할 수도 있고 [ ]안에 직접 넣을 수도 있다.
index는 항상 0부터 시작한다. index덕분에 삽입 삭제가 유용하다.
===============================================
2. Index position
const fruits=['apple','banana'];
console.log(fruits);
=>
- 0: "apple"
- 1: "banana"
여기서 apple에게 접근하고 싶다면
console.log(fruits[0]); =>[ ]안에 해당 index를 넣으면 된다.
마지막 index에 접근하고 싶다면
console.log(fruits[fruits.legnth-1]); 보통 이렇게 쓴다.
=================================================
3. 반복문
const fruits=['apple','banana'];
1) 기본 for문
for(i=0;i<=fruits.length;i++){
console.log(fruits[i]);
}
2) for of
for(let fruit of fruits){
console.log(fruit);
}
3) forEach
forEach는 value, index, array자제를 받아서 콜백해줄 수 있다!
fruits.forEach(function(fruit,index){
console.log(fruit,index);
});
=> apple 0
banana 1
이걸 간단하게 fruits.forEach((fruit,index)=>console.log(fruit,index));
이렇게 표현할 수도 있다.
=>forEach 는 배열 안에 들어있는 값들마다 내가 전달한 함수를 출력한다!
======================================================
4. 배열에 추가, 삭제 복사
push: 배열 끝에 추가
fruits.push("strawberry","cherry");
[apple,banana, strawberry,cherry]
pop : 끝에서부터 지움
fruits.pop();
=>[apple,banana,strawberry]
unshift: 배열 첨부터 추가
fruits.unshift("lemon");
=>[lemon,apple,banana,strawberry]
shift:배열 첨부터 삭제
fruits.shift();
☆★☆
주의 !!
shift와 unshift는 pop,push보다 한참 느리다.!!
왜냐하면 배열의 끝에서 추가 및 삭제를 하는 것은 빈 공간에 데이터를 다루는 것이지만
앞에서 데이터를 조작하면 기존에 있던 데이터를 옮긴다음에 작업이 들어가기 때문이다.
splice: index로 데이터 지우기 혹은 추가!!
fruits.(start:number,)
start=어디서 부터 ,number=몇개나 지울 건가? 만약 number를 입력하지 않으면 start부터 걍 다 지워버림
fruits.splice(1,1,'pineapple',peach')
=>[lemon,pineapple,peach,banana,strawberry]
concat: 두개의 배열을 합친다.
const fruits2=['pear'];
const new fruits=fruits.concat(fruits2);
=>[lemon,pineapple,peach,banana,strawberry,pear]
=============================================================
5. 검색
indexOf
fruits.indexOf('lemon');
=> 0
=>배열안에 없는 것을 호출하면 -1을 출력한다.
fruits.includes("apple");
=>false;
fruits.includes('banana')
=>true;
lastIndexOf
fruits.push('lemon');
=>[lemon,pineapple,peach,banana,strawberry,pear,lemon]
fruits.indexOf('lemon');
=>0
fruits.lastIndexOf('lemon');
=>6