ECMAScript 2019의 유용한 특징

우선, 내가 원하는 만큼 자주 글을 쓰지 못한 것에 대해 사과하겠습니다.미친 듯이 바쁜 2주 동안 나는 DDD Perth 2019에서 재미있는 강연을 많이 했다.
이 점을 감안하여 이번에는 ECMAScript 2019 (aka ES2019 or ES10)에 추가된 새로운 기능을 살펴보고 싶습니다. 왜냐하면 그것들은 매우 흥분되고 우리의 생활을 더욱 가볍게 하기 때문입니다.😎.

TLDR;
언뜻 보기에 이 버전은 Array.prototype, flatflatMap에 내장 함수를 추가하였다.그리고 우리는 Object.fromEntries 직접 Object.entries 의 반환값을 새로운 대상으로 변환했다.
널리 사용되는 비표준 버전trimStarttrimEnd에는 String.prototypeString.prototype.trimLeft가 있습니다.
또 다른 흥미로운 특징은 선택할 수 있는 trimRight 귀속 매개 변수입니다.이외에도 일부 JSON이 개선되었고 catch가 추가되었습니다. 기호에 대한 설명을 지정할 수 있습니다. Symbol.prototype.description는 양식이 좋은 UTF-8을 되돌려주고 입력을 고려하지 않으며 마지막에 해당하는 원시 원본 텍스트나 표준 자리 차지 문자를 되돌려 달라고 요구합니다JSON.stringify.
만약 네가 준비가 다 되었다면, 우리 시작하자.
Function.prototype.toString Array.prototype.{flat, flatMap}는 다차원 그룹에서 1차원 그룹을 만들 수 있는 새로운 방법이다.
다음과 같은 배열이 있다고 가정합니다.
const myArray = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]];
flat() 이전에 이 점을 실현하려면 다음과 같이 해야 한다.
const myNewArray = [].concat.apply([], myArray)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
또는
var myNewArray = myArray.reduce(
  function(prev,curr) {
    return prev.concat(curr)
  }
)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
이 새로운 보충이 있으면 다음과 같이 간단해질 것이다.
var myNewArray = myArray.flat(4);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
여러 통화를 연결할 수도 있습니다.
var myNewArray = myArray.flat().flat().flat().flat();
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
flat 함수의 매개 변수는 그룹을 볼 깊이만 지정합니다.배열의 깊이를 결정하지 못하면 flat를 입력으로 사용하십시오.
var myNewArray = myArray.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
입력을 제공하지 않으면 기본적으로 한 수준 깊이 들어가기만 합니다.
var myNewArray = myArray.flat(); 
// [1, 2, 3, 4, 5, 6, Array(4)];
Infinity 다른 한편, 매개 요소를 매핑 함수로 매핑한 다음 결과를 새 그룹에 평평하게 펼칠 수 있습니다.이것을 flatMap 함수와 map 함수를 연결하는 것으로 볼 수 있다.그러나 그것은 사용과 집행 효율에 매우 유용하다.
let myArray = [1, 2, 3, 4, 5];

let mappedArray = myArray.map(x => [x, x * 2]);
// [Array(2), Array(2), Array(2), Array(2), Array(2)]
// 0: (2)[1, 2]
// 1: (2)[2, 4]
// 2: (2)[3, 6]
// 3: (2)[4, 8]
// 4: (2)[5, 10]

let mappedFlattenedArr = mappedArray.flat();

// [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]

let myNewArray = myArray.flatMap(v => [v, v * 2]);
// [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]
flat이런 방법들이 우리에게 주는 도움은 명백히 알 수 있다.우리의 String.prototype.{trimStart, .trimEnd}trimLeft로 바뀌고 trimStarttrimRight로 바뀐다는 것을 명심하세요.
let message = ' This is a string with white space around ';

message = message.trimStart();
// 'This is a string with white space around '

message = message.trimEnd();
// 'This is a string with white space around'
trimEnd이 방법은 Object.fromEntries를 가져와 키 값을 대상으로 변환합니다.하지만 Iterable:

JavaScript supports a protocol by which objects such as arrays can be used by control structures such as forof and the spread operator ... to loop through data sequentially. This is referred to as the iterable and the data structures that support this functionality are called iterables. While JavaScript provides maps, arrays and sets with an iterable property from the get-go, plain objects do not have this by default.


이 점을 보려면:
let entries = new Map([["name", "john"], ["age", 22]]);

let newObj = Object.fromEntries(entries);
// { name: 'john', age: 22 }
실제 사용 사례는 질의 문자열을 해석할 때입니다.
let query = Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'));

// { foo: 'bar', baz: 'qux' }

캡처 바인딩(옵션)
선택할 수 있는catch 귀속은catch 블록에서 Iterable 인자를 사용하지 않고 try/catch 인자를 사용할 수 있도록 합니다.
이전에는 관심 있든 없든 error 이 문법을 사용해야 했다. 예를 들어, 오래된 브라우저를 지원하는 기능으로 되돌아갈 수밖에 없을 때:
try {
  // try to use a web feature which may not be implemented
} catch (unused) {
  // fall back to a less desirable web feature with broader support
}
사용err:
try {
  // ...
} catch {
  // ...
}
ES2019이 새 설명 속성은 문자열입니다. Symbol.description 대상의 선택할 수 있는 설명을 되돌려줍니다.이 방법으로 대체하는 것을 권장합니다Symbol뭘 돌려줄지 모르겠어요.
let description = 'This symbol represents an emoji 😁';

let mySym = Symbol(description);
// Symbol('This symbol represents an emoji 😁')

console.log(mySym.description);
'This symbol represents an emoji 😁'
Symbol.prototype.toString이 방법은 매우 유용해서 함수의 원본 코드를 되돌릴 수 있다.제3자 함수를 사용하는 코드 블록에 대해 고장 제거를 상상해 보세요.이것은 소스 코드가 있는 것을 고려하여 실현된 것을 보는 데 도움을 줄 수 있습니다.
function myFn(emoji) {
  let msg = `${emoji} is hellav an emoji`;
  console.log(msg);
}

console.log(myFn.toString());

// "function myFn(emoji) {
//   let msg = `${emoji} is hellav an emoji`;
//   console.log(msg);
// }"
물론 만능은 아니다.어레이에서 함수Function.toString를 시도한 경우:
Array.prototype.map.toString();

// "function map() { [native code] }"
JavaScript로 작성된 것이 아니기 때문에, 이 함수가 본체 코드로 작성되었음을 보여 줍니다.
map이 팀은 유니코드 문자를 개선했는데, 현재 이런 방법은 형식이 잘못된 데이터를 되돌릴 수 없습니다.
// Non-BMP characters still serialize to surrogate pairs.
JSON.stringify('𝌆')
// → '"𝌆"'
JSON.stringify('\uD834\uDF06')
// → '"𝌆"'

// Unpaired surrogate code units will serialize to escape sequences.
JSON.stringify('\uDF06\uD834')
// → '"\\udf06\\ud834"'
JSON.stringify('\uDEAD')
// → '"\\udead"'
JSON.stringify 안정성
팀은 정렬을 변경하여 안정적으로 하기로 결정했다. (즉, 비교적 같은 요소는 원시 순서를 유지해야 한다.)
const grades = [
  { topic: 'math', grade: 10 },
  { topic: 'literacy', grade: 10 },
  { topic: 'chemical', grade: 13 },
  { topic: 'geography', grade: 12 },
  { topic: 'modern history', grade: 12 },
  { topic: 'art', grade: 13 },
  { topic: 'computer basics', grade: 14 },
  { topic: 'algebra', grade: 14 },
];

grades.sort(a, b => a.grade - b.grade);

// 0: {topic: "math", grade: 10}
// 1: {topic: "literacy", grade: 10}
// 2: {topic: "geography", grade: 12}
// 3: {topic: "modern history", grade: 12}
// 4: {topic: "chemical", grade: 13}
// 5: {topic: "art", grade: 13}
// 6: {topic: "computer basics", grade: 14}
// 7: {topic: "algebra", grade: 14}

요약
전반적으로 자바스크립트는 정확한 방향으로 발전하여 개발자가 더욱 안정적이고 신뢰할 수 있으며 일치하는 코드를 작성하도록 돕고 있다.너는 그들의 사이트GitHub repo here에서 더 많은 정보를 찾을 수 있다.
JavaScript에서 더 많은 멋진 기능을 보고 곧 다른 기사에서 당신을 만날 수 있기를 바랍니다.

좋은 웹페이지 즐겨찾기