본문 바로가기
웹(web)/프론트엔드-javascript

객체, 배열의 내장함수 정리

by 바코94 2020. 6. 27.

객체 내장함수

let obj = { 

 name: 'bob',

 id : 1

}

를 기준으로 설명한다.

 

속성 이름으로만 이루어진 ["name" , "id"] 데이터를 얻고 싶다면?

Object.keys(obj);

 

속성 값으로만 이루어진 ["bob", 1] 데이터를 얻고 싶다면?

Object.values(obj);

 

속성별 배열로 이루어진 [["name", "bob"], ["id", 1]] 데이터를 얻고 싶다면?

Object.entries(obj);

 

문자열에서 obj.name 값을 사용하고 싶다면?

`my name is ${obj.name}` 

 

 

배열 객체 내장함수

let arr = [1, 2, 3, 4, 5];

를 기준으로 설명한다.

 

선언된 함수를 이용해 모든 배열 값을 출력하고 싶다면?

function print(value) { console.log(value) };

arr.forEach(print);

 

한 줄 만을 사용해 모든 배열 값을 출력하고 싶다면?

arr.forEach(function (value) { console.log(value) };);

 

한 줄 만을 사용해 모든 배열 값을 출력하고 싶다면?

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

 

[1, 4 , 9, 16, 25] 배열을 만들고 싶다면?

function square(n){ return n*n;};

obj.map(square);

 

한 줄로 [1, 4 , 9, 16, 25] 배열을 만들고 싶다면?

arr.map(function(n) { return n * n; });

 

간단한 한 줄로 [1, 4 , 9, 16, 25] 배열을 만들고 싶다면?

arr.map(n => n * n);

 

5의 인덱스 값을 바로 찾고 싶다면?

arr.findIndex(n => n === 1);

 

값 3부터 2개 지우고 싶다면?

arr.splice(3, 2);

 

인덱스 1번째 부터 2번째 까지 원소를 가진 배열 [1,2]를 얻고 싶다면?

arr.slice( 1, 2+1);

 

배열 첫 번째 인덱스의 값을 사용함과 동시에 제거하고 싶다면?

arr.shift();

 

배열 마지막 인덱스의 값을 사용함과 동시에 제거하고 싶다면?

arr.pop();

 

배열 첫 번째 인덱스에 100의 값을 끼워넣고 싶다면?

arr.unshift(100);

 

배열 마지막 인덱스 바로 뒤 자리에 100의 값을 추가하고 싶다면?

arr.push(100);

 

[1,2,3,4,5 , 1,2,3,4,5]를 만들고 싶다면?

arr.concat(arr);

 

'1,2,3,4,5'를 만들고 싶다면?

arr.join();

 

'1, 2, 3, 4, 5'를 만들고 싶다면?

arr.join(', ');

 

'1-2-3-4-5'를 만들고 싶다면?

arr.join('-');

 

배열의 모든 값을 누적한 값을 구하고 싶다면?

arr.reduce((accumulator, current) => accumulator + current, 0);

 

배열의 평균 값을 구하고 싶다면?

arr.reduce( function(accumulator, current, index, array) {

  if (index === array.length - 1)

    return (accumulator + current) / array.length;

  return accumulator + current;

}, 0);

 

객체가 원소인 배열 

items = [ { id: 1, text: 'hello'}, {id:2, text: 'bye'}, {id:3, text: 'hello'}]; 이라고 가정한다.

 

간단한 한 줄로 ['hello' , 'bye', 'hello'] 배열을 만들고 싶다면?

items.map(item => item.text);

 

id가 3인 객체 { id:3, text:'hello'} 를 얻고 싶다면?

items.find(obj => obj.id === 3);

 

text가 'hello'인 객체들만 가지고 배열 [ { id: 1, text: 'hello'}, { id:3, text:'hello'}] 을 얻고 싶다면?

items.filter(obj => obj.text == 'hello');

 

 

'웹(web) > 프론트엔드-javascript' 카테고리의 다른 글

클래스  (0) 2020.06.27
생성자 함수와 상속  (0) 2020.06.27
javascript 추가 기능  (0) 2020.06.27
[Closure]  (0) 2020.06.03
[Execution Context] Function call  (0) 2020.06.03