개발/javascript

자바스크립트 배열 내장 함수(3)

희운1205 2021. 12. 7. 16:05
반응형

1) shift

:  배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환하고, 배열의 길이를 변하게 함

구문

arr.shift()

예1)
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1); // 제거된 나머지 값
결과 : [2, 3]

console.log(firstElement); // 제거된 값
결과 : 1

예2) 반복문에서 조건이 만족할때 까지 제거
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];

while( (i = names.shift()) !== "Paul" ) {
    console.log(i);
}
결과 :
Andrew
Edward

console.log(names);
 ['Chris', 'John']

2) unshift

:  새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환하여 배열의 길이를 변하게 함

구문

arr.unshift([.. 요소])

예1) 
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
결과 : 5

console.log(array1);
결과 : [4, 5, 1, 2, 3]

예2)
var arr = [1, 2];

arr.unshift(0);
console.log(arr);
결과 [0, 1, 2]

arr.unshift(-2, -1); // = 5
console.log(arr);
결과 : [-2, -1, 0, 1, 2]

arr.unshift([-3]);
console.log(arr);
결과 [[-3], -2, -1, 0, 1, 2]

 

3) push

:  배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.

구문

arr.push([.. 요소])

예1) 배열 더하기

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
결과 : 4

console.log(animals);
결과 : ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
결과 : ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

예2) 두개의 배열 합치기

var vegetables = ['설탕당근', '감자'];
var moreVegs = ['셀러리', '홍당무'];

// 첫번째 배열에 두번째 배열을 합친다.
// vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다.
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); 
결과 : ['설탕당근', '감자', '셀러리', '홍당무']

 

4) pop

:  배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

구문

arr.pop()

예1)
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
결과 : "tomato"

console.log(plants);
결과 : ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();
console.log(plants);
결과 : ["broccoli", "cauliflower", "cabbage"]

 

5) concat

:  인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환

구문

arr.concat(배열 1, 배열 2,...)

예1)
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
결과 : ["a", "b", "c", "d", "e", "f"]

예2)
var alpha = ['a', 'b', 'c'];
var numeric = [1, [2, 3]];

var merge = alpha.concat(numeric);
console.log(merge);
결과 : ['a', 'b', 'c', 1, 2, 3]

예3)
var alpha = ['a', 'b', 'c'];
var numeric = [1, [2, 3]];

var merge = alpha.concat(numeric);
console.log(merge);
결과 : ['a', 'b', 'c', 1, Array(2) 0: 2, 1: 3]

 

6) every

:  배열 안의 모든 요소가 주어진 조건을 통과하는지 테스트합니다. Boolean 값을 반환합니다.

구문

 

// 화살표 함수

arr.every((element) => {... } )
arr.every((element, index) => { ... } )
arr.every((element, index, array) => { ... } )

// 콜백 함수
arr.every(callbackFn)
arr.every(callbackFn, thisArg)

// 인라인 콜백 함수
arr.every(function callbackFn(element) { ... })
arr.every(function callbackFn(element, index) { ... })
arr.every(function callbackFn(element, index, array){... })
arr.every(function callbackFn(element, index, array) { ... }, thisArg)

예1) 나이가 18살 이상이면 true
const ages = [32, 33, 16, 40];

var chk = ages.every(checkAge)

function checkAge(age) {
  return age > 18;
}

}
console.log(chk);
결과 : false (모두가 18살이상을 초과하지 않으므로)

예2) 모든 배열의 요소가 10보다 큰지 테스트
function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

예3) 화살표 함수 사용
[12, 5, 8, 130, 44].every(elem => elem >= 10); // false
[12, 54, 18, 130, 44].every(elem => elem >= 10); // true

 

7) some

 배열 안의 요소중 하나라도 주어진 조건을 통과하는지 테스트합니다. Boolean 값을 반환합니다.

구문

arr.some(callback [, thisArg])

예1)
const array = [1, 2, 3, 4, 5];

// 짝수가 하나라도 있으면
const even = (element) => element % 2 === 0;

console.log(array.some(even));
결과: true

예2)  10보다 큰수가 하나라도 있으면)
[2, 5, 8, 1, 4].some(elem => elem > 10);  // false
[12, 5, 8, 1, 4].some(elem => elem > 10); // true
반응형