배열
2023. 4. 16. 21:56ㆍzerobase/javascript
728x90
프로퍼티의 key가 숫자이며 프로퍼티 간의 순서를 가지는 객체
1) 배열 생성 : [] 대괄호나 배열 생성자로 생성
- const array = [];
- const array = new Array(length);
2) 배열 접근
- array[index] -> index는 0부터 시작
const colors = ['red', 'blue', 'green', 'pink', 'mint'];
console.log(typeof colors); // object -> 배열도 객체로 구현한 것이기 때문
console.log(colors[2]); // 인덱스 접근, 인덱스는 0부터 시작 //green
console.log(colors.length); // 자체적으로 length라는 프로퍼티가 있음 //5
3) 배열 관련 함수
- array.pop() 스택
- array.push(value) 스택 , 큐
- array.shift() 큐
4) 배열 특성
- array.length -> 요소 삭제도 가능
- 참조를 통한 복사 (주소 복사)
- for (변수 of array) { }
- array.forEach((변수) => { })
- array.map((변수) => { return })
- 구조 분해 할당 - const [ value1, value2 ] = array;
const colors = ['red', 'blue', 'green', 'pink', 'mint'];
const lastColor = colors.pop(); // 뒤에서
console.log(`${lastColor} popped`); // mint
colors.push('purple'); // 뒤에 넣기
console.log(colors); // [ 'red', 'blue', 'green', 'pink', 'purple' ]
const firstColor = colors.shift(); // 앞에서
console.log(`${firstColor} shift`); // red
console.log(colors); // [ 'blue', 'green', 'pink', 'purple' ]
colors.length = 2; // length 조절로 요소 삭제도 가능
console.log(colors); // [ 'blue', 'green' ]
for (let color of colors) { // for-of로 배열 요소 순차적 조회 가능
console.log(color); //blue, green
}
colors.forEach((color) => { // forEach는 따로 반환하는 값이 없음
console.log(color); //blue, green
})
const newColors = colors.map((color) => { return `new ${color}` }); // map은 내부 함수에서 반환하는 값을 모아서 배열을 다시 만든 후 반환해줌
console.log(newColors); // [ 'new blue', 'new green' ]
const [, newGreen] = newColors; // 구조분해할당 -> 2번째 변수만 받고 싶을 때
console.log(newGreen);
5) 객체를 순차적으로 접근하기
- bject.keys(객체)
- Object.values(객체)
- Object.entries(객체)
const fruits = {
apple: 2000,
mango: 5000,
orange: 1500,
grape: 4000,
kiwi: 8000
};
Object.keys(fruits).forEach((fruitName) => {
console.log(fruitName); //apple , mango, orange, grape, kiwi
})
Object.values(fruits).forEach((price) => {
console.log(price); //2000, 5000, 1500, 4000, 8000
})
Object.entries(fruits).forEach((fruit) => {
console.log(fruit); //[ 'apple', 2000 ], [ 'mango', 5000 ], [ 'orange', 1500 ], [ 'grape', 4000 ], [ 'kiwi', 8000 ]
})