객체의 유형: 배열, 함수, 배열이나 함수가 아닌 객체
배열 기본
const fruits = ['사과', '오렌지', '배', '딸기'];
const arrayOfArray=[[1, 2, 3], [4, 5]];
arrayOfArray[0] = [1, 2, 3]
배의 내부의 값은 중복 되어도 되고, 아무 값이 없는 배열도 만들 수 있습니다.
const everything = ['사과', 1, undefined, true, '배열', null, ''];
const duplicated = ['가', '가', '가', '가', '가'];
const empty=[];
const target = ['나', '다', '라', '마', '바'];
가장 첫번째 요소를 추가하고 싶은 경우
target.unshfit('가');
가장 첫번째 요소를 삭제하고 싶은 경우
target.shift();
가장 뒤에 요소를 추가하고 싶은 경우
target.push('바');
가장 마미작 요소를 삭제하고 싶은 경우
target.pop();
상수이더라도 객체의 내부를 바꾸는 경우는 가능하다.
const는 엄밀한 상수는 아니라고 생각하자
const는 재할당이 안 된다.
const target = ['가', '나', '다', '라', '마'];
target.splice(1, 1);
//1번 인덱스로부터 1개이므로 '나'만 지워진다.
console.log(target);
<실행결과>
["가", "다", "라", "마"]
const target = ['가', '나', '다', '라', '마'];
target.splice(2, 2);
//2번 인덱스로부터 2개이므로 '다', '라'가 지워진다.
console.log(target);
<실행결과>
["가", "나", "마"]
const target = ['가', '나', '다', '라', '마'];
target.splice(2);
//2번 인덱스로부터 끝까지 지우므로 '나', '다', '라', '마' 가 지워진다.
console.log(target);
<실행결과>
["가"]
const target = ['가', '나', '다', '라', '마'];
target.splice(1, 3, '타', '파');
//1번 인덱스로부터 3번 인덱스까지 지우고, '타', '파' 를 추가한다.
console.log(target);
<실행결과>
["가", '마', '타', '파']
배열의 요소를 지우지 않고, 해당 인덱스에 끼워넣기
const arr = ['가', '나', '다', '라', '마']
arr.splice(2, 0, '바')
<실행결과>
["가", '나', '바', '다', '라', '마']
배열에서 요소 찾기
const target = ['가', '나', '다', '라', '마']
const result = target.includes('다');
const result2 = target.includes('카');
console.log(result);
console.log(result2);
<실행결과>
true
false
const target = ['라', '나', '다', '라', '다']
const result = target.indexOf('다');
const result2 = target.lastIndexOf('라');
const result3 = target.indexOf('가');
console.log(result);
console.log(result2);
console.log(result3);
<실행결과>
2
3
-1(해당 요소가 존재하지 않는 경우)
arr배열에서 '라'를 모두 제거 하시오
const arr = ['가', '라', '다', '라', '마', '라']
while(arr.indexOf('라') > -1):
arr.slice(arr.indexOf('라'), 1)
<실행결과>
['가', '다', '마']
주의해야할 점 (잘못된 예시)
const arr = [1, 2, 3, 4, 5]
if(arr.index(1)){
console.log('1 찾았다');
} else {
console.log('1 못찾았다');
}
<실행결과>
1 못찾았다
const arr = [1, 2, 3, 4, 5]
if(arr.index(1)>-1){
console.log('1 찾았다');
} else {
console.log('1 못찾았다');
}
<실행결과>
1 찾았다