본문 바로가기
프로그래밍

자바스크립트 array

by Youngbin Kwon 2020. 7. 22.

위코드 개강(8/17) D-27.

☆ 2주차 mission : array method 중 slice, splice, push, pop, filter, map 을 활영한 함수를 작성해보세요

자바스크립트 Array

1. Slice (참조)

- arr.slice([start[, end]])

- 배열의 일부분을 추출하여 새로운 배열을 리턴하는 함수

let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

 

2. splice (참조)

-  let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

- 기존 배열에 새로운 배열 시작 부분 (start), 삭제 요소 수 (deleteCount), 추가 요소들 (item1, item2...)을 지정하여 구조를 변경하는 함수

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2, 0, 'drum')

// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] 
// removed is [], no elements removed

// myFish 배열의 2번째 index부터, 0개의 요소를 삭제하고, 'drum'이라는 요소를 신규 추가
// myFish 배열은 삭제되는 사항없이 'drum'요소가 추가되고, removed 배열에는 추가되는 요소가 없음
let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
let removed = myFish.splice(3, 1) 

// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"] 

// myFish 배열의 3번째 요소(mandarin) 부터 1개의 요소(mandarine)를 삭제하고, 추가하는 요소는 없음
// myFish 배열은 'mandarin'이 삭제되고, removed 배열에 mandarin이 추가됨

 

3. push (참조)

- arr.push([element1[, ...[, elementN]]])

- 배열의 끝부분에 새롭게 요소들을 추가할 수 있는 함수

let sports = ['soccer', 'baseball']
let total = sports.push('football', 'swimming')

console.log(sports)  // ['soccer', 'baseball', 'football', 'swimming']
console.log(total)   // 4

 

4. pop (참조)

- arrName.pop()

- 배열의 마지막 요소를 제거하는 함수

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin' ] 
console.log(popped); // 'sturgeon'

 

5. filter (참조)

-  let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

- 배열의 요소들 중 특정 조건을 만족하는 요소들만 추출하여 새로운 배열을 리턴하는 함수

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"]

 

6. map (참조)

- let new_array = arr.map(function callback( currentValue[, index[, array]]) { // return element for new_array }[, thisArg])

- 배열의 요소들에 함수를 적용한 결과값으로 새로운  배열을 생성하는 함수

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

댓글