Array 배열
: 자바스크립트의 배열은 유동배열 = 크기와 데이터의 변경이 가능
특징
1. 데이터 타입 혼용 가능 (권장x)
- const myArray = [1, 2, 3, 'a', 'b'];
- 원래 배열은 같은 데이터 타입만 원소로 사용하는 것이 원칙 but! 자바 스크립트에서는 허용
2. 초기값이 없는 빈 배열을 만든 후, 데이터 추가해 사용 가능
- myArray=[ ];
- myArray[0]=1; //0번지에 추가
- myArray[myArray.length]=2; //맨 뒤에 추가
- myArray[myArray.length+3] = 'new'; //배열의 가장끝에서 +3위치에 추가 (이때 비어있는 공간은 undefined)
3. 각 데이터들은 콤마(,)로 분리되고, 분리된 자료는 index를 가진다
- 인덱스는 0부터
- .length : 총길이 확인
4. const로 배열을 선언하면 배열의 값을 변경할 수는 있으나, 배열 자체를 변경할 수 는 없음(객체 등)
5. set, map처럼 clear()가 없음
선언
1. const myArray = new Array(1, 2, 3, 'a', 'b'); // 권장x
2. const myArray = [1, 2, 3, 'a', 'b'];
사용
// 출력, 추가
<script>
const myArray1 = ['a', "b",'c', 1, 2, 3];
console.log(myArray1); //전체 출력
console.log(myArray1.length); //5
console.log(myArray1[2]); // c
console.log(myArray1[myArray1.length-1]); // 마지막 배열 값 3
myArray1[6]=4; //배열의 6번지에 4 추가
myArray1[myArray1.length]='add'; //배열의 가장 끝에 5 추가
myArray1[myArray1.length+3] = 'new'; //배열의 가장끝에서 +3위치에 추가 (이때 배열의 빈 요소는 undefined)
// for문 이용 전체 출력
for(let i=0; i<myArray1.length; i++){
console.log(myArray1[i]);
}
</script>
유사배열(연관배열) : associative Array
: 여러 타입을 섞어쓰는 배열
- 배열 관련 메서드 중 사용할 수 없는 것들이 있음
let assocArrayType = [1, true, 'hong', undefined, {k: 'value'}, ['k','g']];
유사배열(연관배열) 출력
<script>
// 유사배열(연관배열) : associative Array 여러 타입을 섞어쓰는 배열 > 배열 관련 메서드 중 사용할 수 없는 것들이 있음
let assocArrayType = [1, true, 'hong', undefined, {k: 'value'}, ['k','g']];
//전체 출력
console.log(assocArrayType);
for(let i=0; i<assocArrayType.length; i++){
console.log(assocArrayType[i]);
}
// 전체를 따로따로 출력
for(let i=0; i<assocArrayType.length; i++){
if( i == 4){
console.log(assocArrayType[i].k); //k,g 따로보기
} else {
console.log(assocArrayType[i]);
}
}
</script>
배열 삭제
1. arr.splice(index, count) : index위치부터 count개수 만큼 삭제
2. arr.splice(index, count,item) : index위치부터 count개수 만큼 삭제 후 item 삽입
'JS > JS 공부' 카테고리의 다른 글
[JS] 배열의 정렬 sort, reverse (0) | 2023.04.17 |
---|---|
[JS] 배열 관련 메서드 join, push, unshift, pop, shift (0) | 2023.04.17 |
[JS] 반복문 while, for (0) | 2023.04.14 |
[JS] Math & Random 수학관련 함수 (0) | 2023.04.14 |
[JS] 형변환 (0) | 2023.04.14 |