배열이란 무엇이며, 배열을 생성하는 방법, 요소를 참조,갱신,삭제하는 방법과 Array.length 프로퍼티에 대해 정리해본다
배열(array)은 여러 개의 값을 순차적으로 나열한 자료구조. 특정한 요소들을 일렬로 일정하게 모아둔 집합이라고 할 수 있다. JS에 배열이라는 타입은 존재하지 않는다. 배열은 객체 타입니다.
const arr = [19, 44, 'banna', false];
-예시1-
const arr = new Array(3); // 배열의 길이가 3이지만 요소가 비어있는 배열이 생성된다.
console.log(arr) // [empty × 3]
-예시2-
const a = new Array();
console.log(a) // []
-예시3-
const arr1 = new Array(1,2,3);
console.log(arr1) // [1, 2, 3]
-예시4-
const arr2 = new Array("orange","mango","apple");
console.log(arr2) // ["orange","mango","apple"]
-예시5-
const b = Array(1, 2, 3)
console.log(b) // [1, 2, 3]
-예시1-
const arr = Array.of(1)
console.log(arr) // [1]
const arr1 = Array.of(1,2,3)
console.log(arr1) // [1,2,3]
const arr2 = Array.of('string')
console.log(arr2) // ["string"]
const arr = Array.from({length:2, 0:'a', 1:'b'})
console.log(arr) // ["a", "b"]
const arr1 = Array.from('Hello')
console.log(arr1) // ["H", "e", "l", "l", "o"]
- 예시1-
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry']
console.log(numbers[1]) // 2
console.log(fruits[0]) // Apple
-예시2-
const arr = [1, 2];
console.log(arr[3]); // undefined
const arr1 = [1, ,3]
console.log(arr1[1]); // undefined
console.log(arr1[3]); // undefined
let myArray1 = [19, 44, 'good', [100, 200, 500], false]
console.log(myArray1[2]); // 'good'
console.log(myArray1[3]); // [100, 200, 500]
let myArray1[3] = [100, 300, 500]
-중첩된 배열의 요소에 접근하기-
console.log(myArray1[3][0]); // 100
- 예시1 -
const arr = [0];
arr[1] = 1;
console.log(arr) // [0, 1]
console.log(arr.length) // 2
- 예시2 -
const arr1 = [0,1];
arr1[100] = 100;
console.log(arr1); // [0, 1, empty × 98, 100]
console.log(arr1.length) // 101
- 예시 3-
const arr2 = [];
arr2[0] = 1;
arr2['1'] = 2;
console.log(arr2) // [1, 2]
arr2['foo'] = 3
arr2.bar = 4
arr2[1.1] = 5
arr2[-1] = 6
console.log(arr2) // [1, 2, foo: 3, bar: 4, 1.1: 5, -1: 6]
console.log(arr2.length) // 2
let myArray = [19, 44, 'good', false]
myArray[0] = 500
myArray[3] = true
console.log(myArray); // [500, 44, "good", true]
const arr3 = [1, 2, 3]
delete arr3[1];
console.log(arr3) // [1, empty, 3]
console.log(arr.length) // 3
- 예시1-
let myArray = [19, 44, 'good', false]
console.log(myArray.length) // 4
- 예시2-
console.log([1, 2].length) // 2 (리터럴 방식으로 사용)
console.log([].length) // 0
let myArray = [19, 44, 'good', false]
for(let i=0; i< myArray.length; i++){
console.log(myArray[i]);
}
[출력 되는 값]
19
44
"good"
false
let myArray4 = [19, 44, 'good', [100, 200, 500], false]
let myArray5 = [900, 800, 700, 600]
let myArray6 = [7, 77, 777, 7777, 77777, 777777]
console.log(myArray4.length) // 5
console.log(myArray4[myArray4.length-1]); // false
console.log(myArray5[myArray6.length-1]); // 777777