const arr = [1, 2, 3];
// 모두 가능
arr[3] = 'test';
arr['property'] = 'string value';
arr['obj'] = {};
arr['{}'] = [1, 2, 3];
arr['func'] = function () {
return 'hello'
};
// arr은 obj처럼 동작한다고 볼 수 있다.
const obj = {
0 : 1;
1 : 2;
2 : 3;
}
💡 배열이 정말 배열인지 확인할 때?
Array.isArray()
사용하자!!
다만 최신 문법이라 polyfill이 필요할 수 있다
const arr = [1, 2, 3];
arr[3] = 4;
arr[9] = 10;
console.log(arr.length) // 10이 출력
// arr = [1, 2, 3, 4, , , , , , 10]
Array.prototype.clear = function () {
this.length = 0;
}
function clearArray(array) {
array.length = 0;
return array
}
const arr = [1, 2, 3]
// 1.
arr.clear()
console.log(arr) // []
// 2.
console.log(clearArray(arr)) // []
배열의 길이를 0으로 설정하는 것만으로도 배열이 초기화된다.
마지막 인덱스를 return 하는 것에 가깝다
이게 바로 배열의 length를 주의해서 써야하는 이유
// 배열의 인덱스로 접근 -> 값이 나타내는 바가 명확하지 X
inputs[0]
inputs[1]
// 1. 배열 구조 분해 할당
const [firstInput, secondInput] = inputs
// 2. 파라미터에서 미리 분해
function operateTime([firstInput, secondInput], arg1, arg2) {}
배열이 하나의 값만 가지고 있을 때
1. 구조 분해 할당
2. lodash의 _.head(array)
3. util 함수 직접 생성
const arrayLikeObject = {
0 : "HELLO",
1 : "WORLD",
length: 2,
}
const arr = Array.from(arrayLikeObject);
console.log(arr) // ["HELLO", "WORLD"]
console.log(arr.length) // 2
console.log(Array.isArray(arrayLikeObject)); // false
console.log(Array.isArray(arr)); // true
javascript의 arguments, nodelist ➡ 유사 배열 객체
원본 배열이 변경되지 않도록
배열 복사
새로운 배열을 반환하는 메서드 활용 (ex. filter, map, slice ... )
for(let i = 0 ; i < 10; i++) {
console.log(i)
}
이렇게 작성하는 것보다
map
, filter
와 직접 작성한 함수들을 이용해 어떤 작업을 하고 있는지 명시적으로 나타내는 것이 좋다.
const price = ["1000", "2000", "3000"]
const suffixWon = (price) => price + "원";
const isOverOneThousand = (price) => Number(price) > 1000;
const ascendingList = (a, b) => a - b;
function getWonPrice(priceList) {
const isOverList = priceList.filter(isOverOneThousand)
const sortList = isOverList.sort(ascendingList);
return sortList.map(suffixWon);
}
// 배열 메서드 체이닝
function getWonPrice(priceList) {
return priceList
.filter(isOverOneThousand) // filter로 원하는 조건에 맞는 배열 리스트
.sort(ascendingList) // 오름차순 정렬
.map(suffixWon); // '원'을 붙여 배열 요소 다시 정리
}
Array.prototype.forEach()
forEach()
메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.
반환 값 : undefined
Array.prototype.map()
map()
메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
반환 값 : 배열의 각 요소에 대해 실행한 callback
의 결과를 모은 새로운 배열
map
, forEach
, filter
에서 continue와 break 사용 불가능 ➡ 배열 중간에 흐름을 제어하기가 어렵다
💡 대안
1. try-catch
const orders = ["first", "second", "third"];
try{
orders.forEach(function(order){
if(order === "second"){
throw "두번째 입니다"
}
console.log(order)
})
} catch(e) {
}
for ... of(in) 문이나 어쩔 수 없이 일반 for 문 사용하기
아래의 메서드들로 조기 종료 가능
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
참고자료
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach