테스p 2022. 12. 21. 17:12

배열안에 배열도 넣을 수 있꼬, length ㅅㅏ용하면 길이도 알 수 있고, 배열은 0부터 시작하는것도 알고 있쥬~!

팁 : 길이에서 -1 넣으면 마지막요소 찾는거

const el = ['a','b','c']

console.log(el[el.length - 1]); //무줘꽌 마지막요소 찾기 마너일

퀴즈

마지막 배열에서 2번째요소 (el[el.length - 2])v

 

배열 추가하기

const target = ['a','b','c'];
target[3] = 'f';
console.log(target);

배열이 길이가 바뀔수가 있어서 마지막에 추가하고싶은경우

const target = ['a','b','c'];
target[target.length] = 'f';
console.log(target);

length 사용하면 마지막에 추가됨

 

배열 제일 앞에 추가하고싶은경우 : undshift

const target = ['a','b','c'];
target.unshift('f');
console.log(target);

배열에서  첫번째 요소 제거하기 :shift

const target = ['a','b','c'];
target.shift();
console.log(target);

 

배열 제일 뒤에 추가하고싶은경우 : push

const target = ['a','b','c'];
target.push('f');
console.log(target);

 

const 상수더라도 객체 내부의 값은 변경 가능

배열에서  마지막 요소 제거하기 : pop

const target = ['a','b','c'];
target.pop();
console.log(target);

 

 

배열의 중간요소 제거하기 : splice(지우고싶은인덱스, 그리고 그지우고싶은인덱스로 부터 몇개를 지울지)

const target = ['a','b','c','d']
target.splice(1,1)
console.log(target); // ['a', 'c', 'd']

const target = ['a','b','c','d','e','f']
target.splice(2,3) //c부터 3개지울게 cde remove
console.log(target); // ['a', 'b', 'f']

근데 두번째 숫자가 없으면 뒤에있는거까지 싹다 지워버림

const target = ['a','b','c','d','e','f']
target.splice(3) //c부터 뒤에있는건 싹다지울게
console.log(target); //  ['a', 'b', 'c']

 

그리고 추가도 가능함 동시에

const target = ['a','b','c','d','e','f']
target.splice(1,2,'add1','add2');
console.log(target); // ['a', 'add1', 'add2', 'd', 'e', 'f']

1번째요소에서 두개지우고 (bc지움) 그자리를 add1,2로 넣을겡

근데 안지우고 그사이에 넣고싶다면? 

const arr = [1,3,4,5,6];
arr.splice(1,0,2); //먼저 몇번째 요소에 넣을건지 찝고, 나는 1번째요소 그리고 0으로 하나도 안지우고 다음 넣고싶은거넣기

요로코롬 하나도 안지우고 넣을 수 있음

배열에서 요소찾기 : includes 들어있으면 true 안들어있으면 false

const target = ['a','b','c']
const result = target.includes('a');
const result2 = target.includes('f');

console.log(result); //true
console.log(result2); //false

트루폴스는 조건문이나 반복문에 많이 들어가있슈

배열에서 요소를 찾는데 정확한 위치찾기: indexOf(앞에서 몇번째자리 인덱스알려줌), lastIndexOf(뒤에서 몇번째자린지 인덱스로알려줌)

const target = ['a','b','c']
const result = target.indexOf('a');
const result2 = target.lastIndexOf('c');

console.log(result); //0
console.log(result2); //2

없으면 -1 반환해줌

배열 반복문

const target = ['a','b','c']
let i = 0;
while(i < target.length){
	console.log(target[i])
    i++;
}
//a
//b
//c

이걸 for문으로 만든다면?

const target = ['a','b','c']
for(i=0; i < target.length; i++){
	console.log(target[i]);
}