210802_배열내장함수

Hannah·2021년 8월 2일

🐣

목록 보기
3/3
const doggy ={
 name: "멍멍이",
 sound: "멍멍",
 age: 2
 };
 console.log(Object.entries(doggy));
console.log(Object.keys(doggy));
//key값을 배열로 가져옴
console.log(Object.values(doggy));
//key값의 value를 배열로 가져옴.
/* 출력값
[Array(2), Array(2), Array(2)]
0: Array(2)
0: "name"
1: "멍멍이"
1: Array(2)
0: "sound"
1: "멍멍"
2: Array(2)
0: "age"
1: 2
["name", "sound", "age"]
["멍멍이", "멍멍", 2]
*/ 

-for..of / for… in 의 차이

for..in (객체 순환)
for...of ( 배열 값 순환)

-break와 continue
반복문에서 벗어나거나 계속하는 것

for (let i = 0; i < 10; i++){
 if (i === 2) continue;
 console.log(i);
}

출력값은 1 3 4 5 6 7 8 9
continue는 조건에 따라 밑 코드를 생략한다.

*if문이 한줄이라면 { } 블럭으로 묶어주지 않아도 정상적으로 실행 가능

for (let i = 0; i < 10; i++){
 if (i === 2) ;
 console.log(i);
 if(i === 5) break;
}

break는 끝내버린다.

break는 끝나는거, continue는 그 다음거.

-주어진 배열에서 3보다 큰 수만 출력하기
빈배열만들기 -> for문으로 검사 -> if문으로 3보다 크면 새배열에 넣기 -> 리턴

#내장 함수
-forEach

function biggerThanThree(numbers) {
 let big = [];
 for (let i = 0; i < numbers.length; i ++){
   if (numbers[i] > 3){
     big.push(numbers[i]);
   }
 }
 return big;
}
 
const result = biggerThanThree([1,2,3,4,5,6,7]);
console.log(result);

배열 출력함수 간결하게 하기(forEach)

const superheroes = [
 '아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'
]
 
function print(hero){
 console.log(hero);
}
superheroes.forEach(print);


배열 출력함수 간결하게 하기(이름 없는 함수로 바로 선언하여  출력)

const superheroes = [
 '아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'
]
superheroes.forEach(function(hero){
 console.log(hero);
});

배열 출력함수 간결하게 하기( 화살표 함수)

const superheroes = [
 '아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'
]
superheroes.forEach(hero => {
 console.log(hero);
});

-map 함수

const array = [1, 2, 3, 4, 5, 6, 7, 8];
 
const squared = array.map(n => n*n);
 
console.log(squared);

map 같은 경우 배열이 있을 때 전체적으로 변환을 하고 싶을 때 사용하는 내장 함수

const items = [
 {id: 1,  text: 'hello'},
 {id: 2, text: 'bye'}
];
// 위에 객체들의 문자열만 배열로 만들고 싶을 때
 
const texts = items.map(item => item.text);
console.log(texts);

-indexOf

//배열에서 원하는 항목이 어디에 있는지 알려주는 함수
 
const superheroes = ['아이언맨', '토르' ,'캡틴 아메리카', '닥터 스트레인지']
const index = superheroes.indexOf('토르');
console.log(index);

-findIndex

//특정한 값이 아닌 어떤 조건으로 찾고 싶을때)
const todos = [
{id: 1, text: '자바스크립트 입문', done: true},
{id: 2, text: '객체와 배열 배우기', done: true},
{id: 3, text: '함수 배우기', done: true},
{id: 4, text: '배열 내장함수 배우기', done: false}
]

const index = todos.findIndex(todo => todo.id === 3);
console.log(index); // 출력값은 2, id 3의 인덱스 출력

-find(배열안의 값을 반환)

//find도 조건으로 찾음 그 값을 반환
const todos = [
{id: 1, text: '자바스크립트 입문', done: true},
{id: 2, text: '객체와 배열 배우기', done: true},
{id: 3, text: '함수 배우기', done: true},
{id: 4, text: '배열 내장함수 배우기', done: false}
]
const index = todos.find(todo => todo.done === false);
console.log(index);
//출력값 : {id: 4, text: "배열 내장함수 배우기", done: false}

-filter

//filter 특정 조건을 만족하는 원소를 찾아 그 원소로 새로운 배열을 만듦.
const todos = [
{id: 1, text: '자바스크립트 입문', done: true},
{id: 2, text: '객체와 배열 배우기', done: true},
{id: 3, text: '함수 배우기', done: true},
{id: 4, text: '배열 내장함수 배우기', done: false}
]
const taskNotDone = todos.filter(todo => !todo.done);
// !todo.done은 결국 false를 뜻함. 더 간결하게 만들 수 있음.
//기존의 배열을 건드리지 않고 새로운 배열을 만들어냄.
console.log(taskNotDone);
/* 출력값은
(1) [Object]
0: Object
id: 4
text: "배열 내장함수 배우기"
done: false */

-splice와 slice

//splice는 원소를 제거할 때 사용, 제거하는 과정에서 해당원소가 몇번째인지 명시해야함. 기존의 배열을 건드림
const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30);
const spliced = numbers.splice(index, 2);
//index부터 2개, 즉 30,40을 지우겠다는 뜻.
console.log(numbers);
//출력값 10, 20
console.log(spliced);
//출력값 30,40 (제거한 원소들)
//slice는 배열을 잘라내는데 기존의 배열을 건드리지 않음.
const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0, 2);
//인덱스 0부터 인덱스 2 '전'까지 자름(기존의 배열을 건드리지 않음)
console.log(sliced);
// [10, 20]
console.log(numbers);
//[10, 20, 30, 40]

0개의 댓글