Array(배열)
· 약 3분
1. Array 특징
- 동적이라
const
로 선언해도 줄었다가 늘었다가 가능하다.
2. Array 생성
A. 선언
javascript
const array = [];
const array = [1, 2, 3, 4, 5];
B. Array().fill()
javascript
const array = Array(10).fill(0);
console.log(array);
powershell
[
0, 0, 0, 0, 0,
0, 0, 0, 0, 0
]
C. Array.from()
javascript
console.log(Array.from('foo'));
console.log(Array.from([1, 2, 3], (x) => x + x));
console.log(Array.from({length: 100}, (value, index) => index));
powershell
[ 'f', 'o', 'o' ]
[ 2, 4, 6 ]
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99
]
3. Array 요소 추가, 삭제
A. .push()
javascript
array.push(element1[, ...[, elementN]])
javascript
const array = [1, 2, 3];
array.push(4, 5);
console.log(array);
powershell
[ 1, 2, 3, 4, 5 ]
B. .splice()
javascript
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
javascript
const array = [1, 2, 3];
array.splice(2, 0, 4);
console.log(array);
const array2 = [1, 2, 3];
array2.splice(2, 1);
console.log(array2);
powershell
[ 1, 2, 4, 3 ]
[ 1, 2 ]
4. 그 외
A. .join()
javascript
array.join([separator]);
javascript
const array = [1, 2, 3, 4, 5, 6];
console.log(array.join('+'));
powershell
1+2+3+4+5+6
B. .reverse()
javascript
array.reverse();
javascript
const array = [1, 2, 3, 4, 5, 6];
console.log(array.reverse());
powershell
[ 6, 5, 4, 3, 2, 1 ]
B. .concat()
javascript
array.concat([value1[, value2[, ...[, valueN]]]])
javascript
const array = [1, 2, 3, 4, 5, 6];
const array2 = [7, 8, 9];
console.log(array.concat(array2));
powershell
[
1, 2, 3, 4, 5,
6, 7, 8, 9
]