-
배열의 메서드 (array method)Javascript 2020. 3. 26. 22:16
Array
새로운 Array 객체를 생성할 때 사용합니다.
더보기구문
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
매개변수
elementN
배열을 초기화할 때 채워넣을 요소. 단, 항목이 하나뿐이며
그 항목의 자료형이 숫자일 경우 arrayLength 매개변수로 간주한다.
arrayLength
length 속성이 해당 값인 배열을 생성하지만 그 만큼의
빈 슬롯을 가지는 것으로 실제 undefined를 채우는 것이 아닙니다.)
//배열 리터럴 표기법 let fruits = ['사과', '바나나'] console.log(fruits.length) // 2 console.log(fruits[0]) // "사과" //단일 매개변수 배열 생성자 let fruits = new Array(2) console.log(fruits.length) // 2 console.log(fruits[0]) // undefined fruits.length = 5 console.log(fruits.length) // 5Array.isArray
객체가 Array라면 true를 반환하고, 아니라면 false를 반환합니다.
더보기구문
Array.isArray(obj)
매개변수
obj
검사할 객체
반환값
객체가 Array라면 true, 아니라면 false
Array.isArray('문자열') //false Array.isArray(123) //false Array.isArray(words) //true Array.isArray([1, 2, 3]) //true배열과 객체를 분별하려면
function 객체인가(a){ if(typeof a === 'object' && !Array.isArray(a)){ return 'object' } }indexOf
배열에서 지정된 요소를 찾을 수 있는 첫번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.
더보기구문
arr.indexOf(searchElement[, fromIndex])
매개변수
searchElement
배열에서 찾을 요소
fromIndex
검색을 시작할 색인
반환값
배열 내의 요소의 최초의 인덱스. 발견되지 않으면 -1
let words = ['the', 'great', 'black']; words.indexOf('the') // 0 words.indexOf('black') // 2 words.indexOf('없는 단어') // -1 words.indexOf('the') !== -1 // true words.indexOf('없는 단어')!== -1 // falseincludes
배열이 특정 요소를 포함하고 있는지 판별합니다.
더보기구문
arr.include(valueToFind[, fromIndex])
매개변수
valueToFind
탐색할 요소
fromIndex
검색을 시작할 위치
반환값
Boolean 값
let words = ['the', 'great', 'black']; words.includes('the'); // true words.includes('없는 단어'); // false words.includes('the', 3); // false //IE에서 호환되지 않음push / pop
배열에서 마지막 요소를 추가하고(push), 제거(pop)합니다.
더보기구문
arr.push(element1[, ...[, elementN]])
매개변수
elementN
배열의 끝에 추가할 요소
반환값
호출한 배열의 새로운 length 속성
let arr = ['the', 'great']; let total = arr.push('black'); console.log(arr); //['the', 'great', 'black'] console.log(total); //3push로 두개의 배열을 합치기
var vegetables = ['설탕당근', '감자']; var moreVegs = ['셀러리', '홍당무']; // 첫번째 배열에 두번째 배열을 합친다. // vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다. Array.prototype.push.apply(vegetables, moreVegs); console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무']//구문 - arr.pop() //반환 값 - 배열에서 제거한 요소. 빈 배열일 경우 undefined를 반환합니다. let arr = ['the', 'great', 'black']; let popped = arr.pop(); console.log(arr); //['the', 'great'] console.log(popped); //'black'shift / unshift
배열에서 첫 번째 요소를 제거하고(shift), 추가(unshift)합니다.
더보기구문
arr.shift()
arr.unshift([...elementN])
매개변수
elementN (unshift)
배열의 맨 앞에 추가할 요소
반환값
shift 배열에서 제거한 요소. 빈 배열일 경우 undefined를 반환합니다.
unshift 호출한 배열의 새로운 length 속성을 반환합니다.
let arr = ['the', 'great', 'black']; let shifted = arr.shift(); console.log(arr); //['great', 'black'] console.log(shifted); //'the'let arr = ['great', 'black']; let total = arr.unshift('the'); console.log(arr); //['the', 'great', 'black'] console.log(total); //3splice
배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
더보기구문
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
매개변수
start
배열의 시작할 인덱스 입니다.
배열의 길이보다 값이 크다면 배열의 길이로 설정됩니다. (array.length)
음수인 경우 배열의 끝에서부터 세어나갑니다. (array.length -n)
deleteCount
배열에서 제거할 요소의 수입니다.
생략하거나 값이 배열의 길이보다 크면 start부터 모든 요소를 제거합니다.
0 이하라면 어떤 요소도 제거하지 않습니다.
item1, item2, ...
배열에 추가할 요소입니다.
지정하지 않으면 요소를 제거하기만 합니다.
반환값
제거한 요소를 담은 배열
//하나도 제거하지 않고, 1번 인덱스에 'apple'추가 let fruits = ['strawberry', 'banana', 'grape']; let removed = fruits.splice(1, 0, 'apple', 'lemon'); //fruits = ['strawberry', 'apple', 'lemon', 'banana', 'grape'] //removed = []//2번 인텍스에서 한개 요소 제거하고 'apple'추가 let fruits = ['strawberry', 'banana', 'grape']; let removed = fruits.splice(1, 1, 'apple'); //fruits = ['strawberry', 'apple', 'grape'] //removed = ['banana']slice
어떤 배열의 begin부터 end의 이전까지의 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열을 바뀌지 않습니다.
더보기구문
arr.slice([begin[, end]])
매개변수
begin
추출 시작점에 대한 인덱스를 의미합니다.
undefined인 경우에는 0번 인덱스부터 slice합니다.
end
추출을 종료할 0 기준 인덱스입니다.
end인덱스를 제외하고 추출하며 생략되면 배열의 끝까지 추출합니다.
반환값
추출한 요소를 포함한 새로운 배열
(slice는 원본을 대체하지 않습니다. immutable)
let arr = ['the', 'great', 'black'] let all = arr.slice() let color = arr.slice(2) let greedy = arr.slice(0, 5) let end = arr.slice(0, -1) //끝에서 두번째 요소까지 추출, 음수 인덱스는 배열의 끝에서부터의 길이를 나타낸다. //arr contains ['the', 'great', 'black'] //all contains ['the', 'great', 'black'] //color contains ['black'] //greedy contains ['the', 'great', 'black']every / some
배열 안의 모든 요소가(every) / 어떤 요소라도(some) 주어진 판별 함수를 통과하는지 테스트합니다.
더보기구문
arr.(every / some)(callback[, thisArg])
매개변수
callback
각 요소를 시험할 함수, 다음 세가지 인수를 받습니다.
currentValue(처리할 현재 요소), index(처리할 현재 요소의 인덱스),
array(every / some을 호출한 배열)
thisArg
callback을 실행할 때 this로 사용하는 값
반환값
callback이 모든 배열 요소에 대해 참인 값을 반환하는 경우 true, 그 외엔 false
let isBelowThreshold = (currentValue) => currentValue < 40; let arrEvery = [1, 30, 39, 29, 10, 13]; let arrSome = [1, 30, 39, 29, 10, 13, 45, 72, 90]; console.log(arrEvery.every(isBelowThreshold)); // expected output: true console.log(arrSome.some(isBelowThreshold)); // expected output: true'Javascript' 카테고리의 다른 글
정수 메서드 (interger method) (0) 2020.03.30 함수형 프로그래밍 (functional programming) (0) 2020.03.27 문자열 메서드 (string method) (0) 2020.03.26 객체 (object) (0) 2020.03.26 함수 (function) (0) 2020.03.26