const emptyArray = [];
const numberArray = [1, 2, 3, 4, 5];
const emptyArray = new Array(); //[]
const arrayWithLength = new Array(5); // 길이가 5인 빈 배열
const arrayWithElements = new Array(1, 2, 3, 4, 5);
Array.from() 정적 메서드는 순회 가능 또는 유사 배열 객체에서 얕게 복사된 새로운 Array 인스턴스를 생성합니다.
Array.from(배열같은것들, (option)맵핑함수, (option)mapFn 실행 시에 this로 사용할 값)
console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// Expected output: Array [2, 4, 6]
// 숫자 시퀀스 생성하기
// 배열의 각 위치가 `undefined`로 초기화되므로
// 아래 'v'의 값은 `undefined`가 됩니다.
let arr = Array.from({ length: 5 }, (v, i) => i);
// [0, 1, 2, 3, 4]
//맵핑함수의 매개변수는 value, index
let arr1 = Array.from(Array(5), function (v, k) {
return k + 1;
});
{ length: 5 }: 이것은 유사 배열 객체입니다. length 속성만을 가진 객체로, 실제로는 값이 비어 있지만 길이가 5인 배열을 생성할 수 있습니다.
(v, i) => i: 이것은 배열의 각 요소를 어떻게 생성할지를 정의하는 함수입니다. 여기서 v는 값(value), i는 인덱스(index)를 나타냅니다. 이 함수는 인덱스를 반환하므로, 결과 배열은 [0, 1, 2, 3, 4]가 됩니다.
똑같은 수로 초기화할 때 사용
fill(value, (옵션)start, (옵션)end) 초기화할 범위인덱스 (start, end]
const arr = new Array(5);
arr.fill(0); // [0, 0, 0, 0, 0]
const arr2 = [1, 2, 3];
arr2.fill('a'); // ['a', 'a', 'a']
const arr3 = [true, false, true];
arr3.fill(false); // [false, false, false]
const arr = new Array(4);
arr.fill(null); // [null, null, null, null]
const arr2 = [1, 2, 3];
arr2.fill(undefined); // [undefined, undefined, undefined]
const arr = new Array(3);
arr.fill([1, 2, 3]); // [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
const obj = { name: 'John' };
const arr2 = [obj, obj, obj];
arr2.fill({ age: 30 }); // [{ age: 30 }, { age: 30 }, { age: 30 }]
2차원배열 만들기
const create2DArray = (rows, cols, initialValue = 0) =>
Array.from({ length: rows }, () => Array(cols).fill(initialValue));
console.log(create2DArray(3, 4));
// [
// [0, 0, 0, 0],
// [0, 0, 0, 0],
// [0, 0, 0, 0]
// ]
const arr = new Array(3);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(4).fill(1); // 크기가 4이고, 1로 채워진 배열 생성
}
arr[0][0] = 10;
console.log(arr[0][0]); // 10
console.log(arr[1][0]); // 1
console.log(arr[2][0]); // 1