티스토리 뷰

반응형

배열 선언

//배열 선언
let arr = [1, 2, 3, "hello", null, true, []];

배열 길이

//배열의 길이
arr.length;  //결과:7

원소 추가

//배열 원소 추가
arr[2] = 99;  //[ 1, 2, 99, 'hello', null, true, [] ]
arr.push(3);  //[ 1, 2, 99, 'hello', null, true, [], 3 ]

배열과 관련된 함수들

//indexOf(): 배열에 특정 값이 있는지 확인
arr.indexOf(99);  //2

//join(): 배열을 문자열로 반환
arr.join();     //1,2,99,hello,,true,,3
arr.join('');   //1299hellotrue3
arr.join('+');  //1+2+99+hello++true++3

//concat(): 배열을 합침
arr.concat(500, 600); //[ 1, 2, 99, 'hello', null, true, [], 3, 500, 600 ]

//...: spread operator. concat()과 동일하게 작동
let arr2 = [...arr, 'a', 'b']; //[ 1, 2, 99, 'hello', null, true, [], 3, 'a', 'b' ]

//forEach(): 배열 요소 각각에 대해 함수를 실행
arr.forEach(function(value){
  console.log(value);
});

arr.forEach(value => console.log(value));

//map(): 배열 요소 각각에 대해 함수를 실행 후 결과를 모아 새로운 배열 반환
const mapped = arr.map(function(value){
  return value * 2;
});

const mapped = arr.map(value => value * 2);

//filter(): 배열 요소 각각에 대해 조건을 만족한 요소를 모아 새로운 배열 반환
const filtered = arr.filter(function(value){
  return typeof value == 'number';    //[ 1, 2, 99, 3 ]
});

const filtered = arr.filter(value => typeof value == 'number');

참조

https://www.boostcourse.org/web316/lecture/16745/
spread operator - https://sheldhe93.tistory.com/13
forEach() - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
map() - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
filter() - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

반응형

'Language > Javascript' 카테고리의 다른 글

DOMContentLoaded 이벤트  (0) 2020.12.30
객체와 객체 탐색  (0) 2020.12.28
appendChild(), insertBefore()  (0) 2020.12.27
parentElement, parentNode  (0) 2020.12.26
querySelector(), getElementById()  (0) 2020.12.26
댓글
Total
Today
Yesterday
링크