변수에는 JavaScript에서 사용할 수 있는 다양한 타입의 값을 할당할 수 있지만 하나의 변수에는 하나의 값만 넣을 수 있었다. 만약 페이스북이나 카카오톡 같은 대규모 서비스에서 여러 개의 데이터를 한 번에 처리할 수 없다면 매번 새로운 변수를 선언하는 일을 반복해야 할 것이다.
그렇다면 여러 개의 데이터를 한 번에 처리하는 방법은 없을까? 대량의 데이터를 쉽게 다룰 수 있게 해주는 데이터 타입은 바로 배열과 객체이다. 배열이나 객체를 사용하면 여러 번의 선언과 할당을 해야만 했던 작업을 단 한 번의 선언으로 해결할 수 있다.
// index [0][1][2][3][4]
let arr = [1, 2, 3, 4, 5];
let arr = [1, 2, 3, 4, 5];
arr[2]; // 3
arr[5]; // undefined
arr[-1]; // undefined
let test = [[1, 2], [3, 4], [5, 6]];
test[1]; // [3, 4]
test[2][1]; // [6]
let arr = [1, 2, 3, 4, 5];
arr[2] = 100;
console.log(arr); // [1, 2, 100, 4, 5]
let arr = [];
arr === [] // false
arr.length === 0 // true
let num = [10, 20, 30, 40, 50];
let sum = 0;
for(let i = 0; i < num.length; i++) {
sum += num[i];
}
console.log(sum); // 150
let arr = ['one', 'two', 'three', 'four', 'five'];
arr.length; // 5
Array.isArray(obj)
let arr = ['one', 'two', 'three', 'four', 'five'];
typeof arr; // 'object'
Array.isArray(arr); // true
arr.push(element1[, ...[, elementN]])
let arr = ['one', 'two', 'three', 'four', 'five'];
arr.push('six'); // 6
console.log(arr); // ['one', 'two', 'three', 'four', 'five', 'six']
arr.pop(); // 'six'
console.log(arr); // ['one', 'two', 'three', 'four', 'five']
arr.unshift('zero'); // 6
console.log(arr); // ['zero', 'one', 'two', 'three', 'four', 'five']
arr.shift(); // 'zero'
console.log(arr); // ['one', 'two', 'three', 'four', 'five']
arr.indexOf(searchElement[, fromIndex])
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.indexOf('e'); // 4
arr.indexOf('f'); // -1
arr.indexOf('a') !== -1 // true
arr.includes(valueToFind[, fromIndex])
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.includes('a'); // ture
arr.includes('f'); // false
arr.join([separator])
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.join(''); // 'abcde'
arr.join(' '); // 'a b c d e'
arr.join('-'); // 'a-b-c-d-e'
slice(start[, end])
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.slice(1, 4); // ['b', 'c', 'd']
arr.slice(-4, 4); // ['b', 'c', 'd']
arr.slice(-2); // ['d', 'e']
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.splice(2, 0, 'x', 'y'); // []
console.log(arr); // ['a', 'b', 'x', 'y', 'c', 'd', 'e']
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.splice(0, 3); // ['a', 'b', 'c']
console.log(arr); // ['d', 'e']
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.splice(1, 3, 'x'); // ['b', 'c', 'd']
console.log(arr); // ['a', 'x', 'e']