let myArray = ['a', 'b', 'c', 'd'];
push pop은 각각 배열의 끝에 요소를 추가하거나 제거한다.
myArray.push('e') // 결과 : myArray = ['a', 'b', 'c', 'd', 'e']; myArray.pop() // 결과 : myArray = ['a', 'b', 'c'];
unshift shift는 각각 배열의 처음에 요소를 추가하거나 제거한다.
myArray.unshift('e') // 결과 : myArray = ['e','a', 'b', 'c', 'd']; myArray.shift() // 결과 : myArray = ['b', 'c', 'd'];
myArray.slice(2) // 결과 : ['c', 'd']; myArray.slice(1,3) // 결과 : ['b', 'c']; myArray.slice(-2) // 결과 : ['c', 'd'];
myArray.splice(start[, deleteCount[,item1[,item2[..])
//ex) myArray.splice(1, 0, 'ABC'); // 결과 : Array ['a', 'ABC', 'b', 'c', ''d]
concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.
const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); ------------------- console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]
forEach() 주어진 함수를 배열 요소 각각에 대해 실행합니다.
myArray.forEach(function(element) { console.log(element); }); // 결과: a, b, c, d
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
const array1 = [10, 40, 90, 160]; // pass a function to map const map1 = array1.map((x) => x * 10); ----------------- console.log(map1); // expected output: Array [100, 400, 900, 1600]
filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4 console.log(beasts.indexOf('giraffe')); // expected output: -1
includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.
const array1 = [1, 2, 3]; ------------------------ console.log(array1.includes(2)); // expected output: true const pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // expected output: true console.log(pets.includes('at')); // expected output: false