변수 하나만으로는 데이터 전송이 비효율적이다. 배열과 객체를 이용하여 효율적인 데이터 전송이 가능하다. 그 중에서도 배열을 배워보자. 배열 메서드만 잘 알아도 데이터를 잘 정제할 수 있다.
배열은 순서가 있는 값. 배열은 대괄호(square bracket)으로 만들고, 값을 요소(element)라고 부르고 쉼표(comma)로 구분한다.
이 순서는 인덱스(Index)라고 부르며 각 요소들은 인덱스를 가지고 있다. 첫번째는 0부터 시작하며 순서대로 1씩 늘어난다.
인덱스로 조회하고 변경하는 방법
let num = [1,2,3,4,5]
num[3] // => 4
num[3] = 200;
변수 재할당하는 것처럼 하면 변경이 된다.
let num = [[1,2],[3,4],[5,6]]
num[0] // => [1,2];
num[0][1] // => 2;
위와 같이 배열도 하나에 인덱스로 취급이 되며, 조회하고 싶은 인덱스를 한 차례 더 적어주면 조회가 된다.
각 요소 출력
let num = [16, 81, 32, 39];
for(n=0; n < num.length; n++){
console.log(num[n]);
}
덧셈
let num = [50, 30, 20, 10];
let sum = 0;
for(n = 0; n < num.length; n++){
sum += num[n];
}
console.log(sum); // => 110
배열에는 기본적인 메서드가 있다. 이걸 잘 활용하면 내가 원하는 데이터만 잘 뽑아서 사용할 수 있다.
typeof로 string, number 등 많은 type을 구분 할 수 있었지만, typeof Array를 하게되면 'object'라고 출력이 된다.
isArray()를 사용하여 Boolean을 출력한다.
Array.isArray('string') // => false;
Array.isArray(Array) // => true;
배열의 요소를 배열 뒤에 추가하거나 제거할 수 있다.
let fruits = ['banana', 'strawberry'];
fruits.push('apple')
console.log(fruits) // => ['banana', 'strawberry', 'apple'];
fruits.pop()
console.log(fruits) // => ['banana', 'strawberry']
push()는 뒤에 추가, pop() 뒤에서 뽑아내기.
✏️let a = Array.pop()을 하면 마지막 요소를 변수 a에 할당할 수 있다. push()의 return 값은 변경된 배열의 길이다.
주의해야할 점은 배열을 변경하는 것이기 때문에 기존 데이터가 없어진다는 점이다.
배열의 요소를 배열 앞에 추가하거나 제거할 수 있다.
let fruits = ['banana', 'strawberry'];
fruits.shift();
console.log(fruits) // ['strawberry']
fruits.unshift('banana');
console.log(fruits) // ['banana', 'strawberry']
shift() 앞에서 뽑아내기, unshift() 앞에 추가하기
✏️let a = Array.shift()을 하면 첫번째 요소를 변수 a에 할당할 수 있다. unshift()의 return 값은 변경된 배열의 길이다.
주의해야할 점은 배열을 변경하는 것이기 때문에 기존 데이터가 없어진다는 점이다.
let Heroes = ['BatMan', 'SpiderMan', 'IronMan'];
console.log(Heroes.indexOf('SpiderMan')); // => 1;
console.log(Heroes.indexOf('Joker')); // => -1;
console.log(Heroes.includes('IronMan')) // => true;
type string에서도 쓰이는 메서드. 주의할 점 => 원본 배열은 바뀌지 않는다.
let Heroes = ['BatMan', 'SpiderMan', 'IronMan', 'Doctor Strange'];
console.log(Heroes.slice(2)); // => ['BatMan','SpiderMan']
console.log(Heroes.slice(2,4)); // => ['IronMan']
console.log(Heroes.slice(-2)); // => ['IronMan', 'Doctor Strange']
console.log(Heroes.slice(2, -1)); // => ['IronMan']
string에 쓰이는 메서드지만 반환은 배열로 한다.
let str = "Hello World"
console.log(str.split(' ')) // => ['Hello', 'World']
배열의 모든 요소를 연결해 하나의 문자열로 만든다. 배열 메서드지만 반환은 string으로.
const alphabet = ['a', 'b', 'c', 'd']
console.log(alphabet.join()); // => 'a,b,c,d' 콤마로 구분하고 합쳐서 한 문자열이 된다.
console.log(alphabet.join(''); // => 'abcd'
console.log(alphabet.join('-'); // => 'a-b-c-d'
배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경.
Array.splice(2,0,'apple') // => 아무것도 제거하지 않고 인덱스 2자리에 'apple'을 추가 한다.
Array.splice(2,1, 'banana') // => 인덱스 2 자리의 요소를 제거하고 그 자리에 'banana'를 추가한다.
Arrat.splice(2); // => 인덱스 2를 포함해서 이후의 모든 요소 제거
인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환. 기존 배열은 건들지 않는다.
const array1 = ["A", "B", "C", "D"];
const array2 = ["E", "F"];
const array3 = array1.concat(array2);
console.log(array3) // => ["A", "B", "C", "D", "E", "F"]
배열에서 문자열을 반환하거나 문자열에서 배열을 반환하거나, 추가, 제거할 때 원본을 건드리느냐 등등 이런 걸 중점적으로 공부해야겠다.