[Javascipt] ECMAScript 2015(ES6) 그 이후 - (2) 문자열, 배열, 객체

2025. 5. 28. 09:00Javascript/Javascript

728x90
반응형

 

 

자바스크립트의 혁명이라 할 수 있는 ECMAScript 2015(ES6) 이후 추가된 자바스크립트 최신 문법 중 자주 이용할 만한 기능들을 추려 정리해 보려 한다.

 

들어가기에 앞서 😡은 과거의 문법을, 😊은 최신 문법을 의미한다는 점을 참고해 봐주시길 바란다.

 

 

 

문자열 최신 문법

 

String.prototype.replaceAll()

  • 일치하는 모든 문자열을 replace
  • String.prototype.replace()는 처음 일치하는 문자열만 바꾸는 것이므로 과거에는 추가적으로 정규 표현식을 사용해 왔지만 이제는 그럴 필요가 없어짐.
// 😡
console.log("문자열에서 여러번 나오는 문자열을 한꺼번에 변경할 수 있습니다.".replace(/문자열/g,""));
// 에서 여러번 나오는 을 한꺼번에 변경할 수 있습니다.

// 😊
console.log("문자열에서 여러번 나오는 문자열을 한꺼번에 변경할 수 있습니다.".replaceAll("문자열",""));
// 에서 여러번 나오는 을 한꺼번에 변경할 수 있습니다.

 

 

 

String padding

  • 문자열의 끝부분이나 시작 부분을 다른 문자열로 채워 주어진 길이를 만족하는 새로운 문자열을 만들어냄.
"hello".padStart(6); // " hello"
"hello".padEnd(6); // "hello "
"hello".padStart(3); // "hello" // 문자열 길이보다 목표 문자열 길이가 짧다면 채워넣지 않고 그대로 반환
"hello".padEnd(20, "*"); // "hello***************" // 사용자가 지정한 값으로 채우는 것도 가능

 

 

 

String.prototype.trimeStart / trimEnd

  • 빈 공간을 제거하는 trim을 좀 더 세부화
// trimStart()
'Testing'.trimStart() //'Testing'
' Testing'.trimStart() //'Testing'
' Testing '.trimStart() //'Testing '
'Testing '.trimStart() //'Testing '

// trimEnd()
'Testing'.trimEnd() //'Testing'
' Testing'.trimEnd() //' Testing'
' Testing '.trimEnd() //' Testing'
'Testing '.trimEnd() //'Testing'

 

 

 


 

 

배열 최신 문법

 

Array.prototype.flat()

  • 중첩 배열 삭제 / 빈공간 삭제
// 중첩 다차원 배열 평평하게
const array = [1, [2, 3], [4, 5]];
array.flat(1); // 결과 : [1,2,3,4,5]

// 데이터 정리도 됨
const entries = ["bob", "sally", , , , , , , , "cindy"];
entries.flat(); // 결과 ['bob', 'sally', 'cindy'];
// flat()
['Dog', ['Sheep', 'Wolf']].flat()
//[ 'Dog', 'Sheep', 'Wolf' ]

// flatMap()
let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x=>x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]

 

 

 

Array.prototype.at()

  • at() 함수를 통해 양수 및 음수 인덱스를 모두 사용하여 문자열을 인덱싱할 수 있음.
const arrays = ['a','b','c','d'];
console.log(arrays.at(-1)); // 'd'

 

 


 

 

객체 최신 문법

 

Optional chaining

  • ?. 문법
  • 프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 접근할 수 있음.
  • ?.은 ?. 앞의 평가 대상이 undefined나 null이면 평가를 멈추고 undefined를 반환. 평가 대상이 true면 쭉쭉 이어나가 최종 값을 반환.
const person1 = {
  name: 'Ellie',
  job: {
    title: 'S/W Engineer',
    manager: {
      name: 'Bob',
    },
  },
};

const person2 = {
  name: 'Bob',
};


// 😡😡😡😡😡
function printManager(person) { // 중첩 객체의 값을 불러오는 함수
  console.log(person.job.manager.name);
}
printManager(person1); // Bob
printManager(person2); // 에러


// 😡
function printManager(person) {
  console.log(person.job && person.job.manager && person.job.manager.name);
}
printManager(person1); // Bob
printManager(person2); // undefined


// 😊
function printManager(person) {
  console.log(person?.job?.manager?.name);
}
printManager(person1); // Bob
printManager(person2); // undefined

 

 

?.() 함수 접근

let user1 = {
  admin() {
    alert("관리자 계정입니다.");
  }
}

let user2 = {};

user1.admin?.(); // 관리자 계정입니다.
user2.admin?.(); // undefined

 

 

?.[] key 접근

let user1 = {
  firstName: "Violet"
};

let user2 = null; // user2는 권한이 없는 사용자라고 가정해 보자.

let key = "firstName";

alert( user1?.[key] ); // Violet
alert( user2?.[key] ); // undefined

alert( user1?.[key]?.something?.not?.existing); // undefined

 

 

 

globalThis

  • globalThis는 환경에 관계 없이 전역 객체를 통일된 방법으로 참조할 수 있는 방법이다.
  • 원래는 브라우저에서의 전역(window)과 노드에서의 전역(global)이 달랐는데 이를 통일한 것으로 보면 됨.
// browser environment
console.log(globalThis);    // => Window {...}

// node.js environment
console.log(globalThis);    // => Object [global] {...}

// web worker environment
console.log(globalThis);    // => DedicatedWorkerGlobalScope {...}

 

 

 

 

 

 

728x90
반응형