[TIL # 19] JS 6일차

Yejin Yang·2022년 4월 28일
0

[TIL]

목록 보기
19/67
post-thumbnail

표준 내장 객체(=메소드)

Array 표준 내장 객체

// 배열 메소드는 콜백을 사용한다.

// Array.length
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4


// Array.prototype.concat()
// 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다. 
// 기존 -> 원본, 주어진 배열, concat은 새로운 배열 반환
const arr = [1, 2, 3, 4] //기존 배열
console.log(
  arr.concat(4, 5, 6) // 주어진 배열
)
// expected output: [1, 2, 3, 4, 5, 6]

// 기존배열.concat([새로운배열1], [새로운배열2], [새로운배열3] ...) - 합치기 가능

// Array.prototype.every()
// 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다. 
// Boolean 값을 반환합니다.
// 콜백 함수를 넣어야 함 배열메소드에들어가는 콜백은 배열의 아이템 갯수만큼 반복함. 
console.log(
  arr.every(item => {
    return item < 5 // 4번 반복 후, 전부 truthy여야지만 참이라고 반환
  })
)
// 간소화 버전(return키워드만 있어서)
console.log(
  arr.every(item => item < 5)
)

// Array.prototype.filter()
// 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
// 원본 손상 X
console.log(
  arr.filter(item => {
    return item < 3
  })
)
console.log(arr) // expected output: [1, 2]
// filter는 원본배열에서 갯수가 줄어든 배열이 나올수있다. 이경우 배열 lengtb 4에서 2로됨 


//Array.prototype.find()
// 어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.
console.log(
  arr.find(element => {
    return element < 3
  })
)
console.log(arr) // expected output: 1


//Array.prototype.findIndex()
// 주어진 판별 함수(콜백)를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 
// 만족하는 요소가 없으면 -1을 반환합니다.
console.log(
  arr.findIndex(item => {
    return item === 3
  })
)
console.log(arr) // // expected output: 2 (index번호라 0 1 2번째에 있어서 2)

// 응용 버전
// 1번째 아이템을 하나 지워라, 근데 인덱스 번호모른다면? findIndex
arr.splice(
  arr.findIndex(item => item === 3), 1
)

// Array.prototype.forEach()
// 주어진 함수를 배열 요소 각각에 대해 실행합니다.
console.log(
  arr.forEach()
)
// console.log(arr)

// 셋다 동일 함. 뭐가 더 편리할까? 3번 각.
// for - 멈추기 가능. break 
for (let i = 0; i < arr.length; i += 1) {
  console.log(arr[i])
}

// for of
for (const item of arr) {
  console.log(item)
}

// forEach - 반복을 멈출 수 가 없어~ 반복 갯수는 무조건 전부 반복해야함
arr.forEach(() => {
  console.log(item)
})

// Array.prototype.includes()
// 배열이 특정 요소를 포함하고 있는지 판별합니다.
console.log(
  arr.includes(4) //true
)

//Array.prototype.join()
// 배열의 '특정한 기호를 기준으로' 모든 요소를 연결해 하나의 문자열로 만듭니다.
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"


// Array.prototype.map()
// 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
// arr.map(callback(currentValue[, index[, array]])[, thisArg])
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]

// Array.prototype.pop()
// 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.
// 원본 배열 수정 O
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// expected output: "tomato"
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

// Array.prototype.shift() 
//  배열에서 '첫 번째 요소'를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.
const array2 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1

// Array.prototype.push()
// 배열의 끝에 하나 이상의 요소를 '맨 뒤에' 추가하고, 배열의 새로운 길이를 반환합니다.
// 원본 수정 O
const animals = ['pigs', 'goats', 'sheep'];
console.log(
  animals.push('cat', 'dog')
)
console.log(animals) // ['pigs', 'goats', 'sheep' 'cat', 'dog']

// Array.prototype.unshift()
// 새로운 요소를 배열의 '맨 앞쪽에 추가'하고, 새로운 길이를 반환합니다.
const array3 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

reduce

for문 대신 내장 메소드인 reduce를 활용하기 좋음

const arr = [1, 2, 3, 4]

// Array.prototype.reduce()
// 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
// 리듀서 함수는 네 개의 인자를 가집니다.
// 누산기 (acc) 현재 값 (cur) 현재 인덱스 (idx) 원본 배열 (src)

const sum = arr.reduce((acc, cur) => {
  return acc + cur // 첫번째 반복은 acc 0, cur은 1 더한 값 1이 return키워드를 통해 다시 반복해서 1, 2 = 3반복
}, 0)
console.log(sum)

// Array.prototype.reverse()
// 호출한 배열을 반전하고 원본 배열을 변형하며 그 참조를 반환
// 원본 수정 O
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]


// Array.prototype.slice()
// 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 
// 원본 배열은 바뀌지 않습니다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"] // 직전까지 반환

// Array.prototype.some()
// 배열 안의 어떤 한 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.
arr.some(item => {
  return item === 1
})
// true

// Array.prototype.splice() 
// 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
// .splice(인덱스, 삭제개수, 추가할 데이터)
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

Object 표준 내장 객체

// Object.assign() 
// 출처 객체들의 모든 열거 가능한 자체 속성을 복사해 대상 객체에 붙여넣습니다. 그 후 대상 객체를 반환합니다.
// Object.assign 프로토타입 메소드가 아님, 정적 메소드 static 
const target = { a: 1, b: 2 }; // 넣어지는 배열 
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }


const userA = {
  name: 'Heropy',
  age: 85
}

const userB = {
  name: 'amy',
  isValid: true
}

const userB = {
  name: 'yejin'
}

Object.assign(userB, userA, userC) // 대상객체 userB, 그외 출처객체임, 대상객체는 하나임. 첫번째에 입력
console.log(userB)
//출처 객체는 수정이 되지않음 복사만 해오는 거라서 

// 만약 userB에도 값이 들어있고, 수정되지 않길 원한다면? 빈 객체를 앞에 추가 입력
const res = Object.assign({}userB, userA, userC)
console.log(res)
// Object.entries()
// 주어진 객체 자체의 enumerable 속성 [key, value] 쌍의 배열을 반환합니다
const userA = {
  name: 'Heropy',
  age: 85,
  isValid: true
}

for (const item of Object.entries(userA)) {
  console.log(item[0]) // key
  console.log(item[1]) // value
}

// Object.keys()
// 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환합니다.
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]

// Object.values() 
// 전달된 파라미터 객체가 가지는 (열거 가능한) 속성의 값들로 이루어진 배열을 리턴합니다. 

Data 표준 내장 객체

Date.prototype.getHours()

Date.prototype.getDay()

Date.prototype.getFullYear() 등등..

console.log(moment().format('YYYY년 MM월 DD일 HH:mm:ss dddd'))
// 2022년 04월 26일 20:26:12 Tuesday
// moment는 전역속성

활용 사이트
https://momentjs.com/
https://day.js.org/

profile
Frontend developer

0개의 댓글