国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Object.fromEntries method
Object.fromEntries method support situation
Array.prototype.flat method
Array.prototype.flat method support situation
Array.prototype.flatMap method
Array.prototype.flatMap method support situation
String.trimStart and String.trimEnd methods
String.trimStart and String.trimEnd methods support situation
Optional catch binding
Support for optional catch binding
Changes to Function.toString() method
Support of Function.toString() method
Home Web Front-end CSS Tutorial All the New ES2019 Tips and Tricks

All the New ES2019 Tips and Tricks

Apr 18, 2025 am 10:19 AM

All the New ES2019 Tips and Tricks

ES2019 brings several new features to the ECMAScript standard. These features are officially available in Node.js, Chrome, Firefox, and Safari. To support older browsers, you can also use Babel to compile these features into different versions of JavaScript.

Let's see what new features are available!

Object.fromEntries method

ES2017 introduces the Object.entries method, which converts objects into their array representations. For example:

 let students = {
  amelia: 20,
  beatrice: 22,
  cece: 20,
  deirdre: 19,
  eloise: 21
}

Object.entries(students) 
// [
// [ 'amelia', 20 ],
// [ 'beatrice', 22 ],
// [ 'cece', 20 ],
// [ 'deirdre', 19 ],
// [ 'eloise', 21 ]
// ]

This is very useful because it allows objects to use a number of functions built into array prototypes such as map , filter , reduce , etc. However, converting the result back to the object requires a relatively tedious process.

 let students = {
  amelia: 20,
  beatrice: 22,
  cece: 20,
  deirdre: 19,
  eloise: 21
}

// Convert to an array to use the .filter() function let overTwentyOne = Object.entries(students).filter(([name, age]) => {
  return age >= 21
}) // [ [ 'beatrice', 22 ], [ 'eloise', 21 ] ]

// Convert multidimensional array back to object let DrinkingAgeStudents = {}
for (let [name, age] of overTwentyOne) {
    DrinkingAgeStudents[name] = age;
}
// { beatrice: 22, eloise: 21 }

Object.fromEntries method is designed to eliminate this loop! It provides cleaner code to facilitate you to use array prototype methods on objects.

 let students = {
  amelia: 20,
  beatrice: 22,
  cece: 20,
  deirdre: 19,
  eloise: 21
}

// Convert to an array to use the .filter() function let overTwentyOne = Object.entries(students).filter(([name, age]) => {
  return age >= 21
}) // [ [ 'beatrice', 22 ], [ 'eloise', 21 ] ]

// Convert multidimensional array back to object let DrinkingAgeStudents = Object.fromEntries(overTwentyOne); 
// { beatrice: 22, eloise: 21 }

It should be noted that arrays and objects are different data structures, and converting between the two can lead to data loss. The following example shows how an array element becomes a duplicate object key:

 let students = [
  [ 'amelia', 22 ], 
  [ 'beatrice', 22 ], 
  [ 'eloise', 21], 
  [ 'beatrice', 20 ]
]

let studentObj = Object.fromEntries(students); 
// { amelia: 22, beatrice: 20, eloise: 21 }
// The first beatrice was discarded!

Be aware of potential side effects when using these functions.

Object.fromEntries method support situation

Chrome Firefox Safari Edge
75 67 12.1 Not supported

Array.prototype.flat method

Multidimensional arrays are a very common data structure, especially when retrieving data. The ability to flatten multidimensional arrays is necessary. Although it could have been done before, the method is not elegant.

Let's look at an example where map function returns a multidimensional array that needs to be flattened.

 let courses = [
  {
    subject: "math",
    numberOfStudents: 3,
    waitlistStudents: 2,
    students: ['Janet', 'Martha', 'Bob', ['Phil', 'Candace']]
  },
  {
    subject: "english",
    numberOfStudents: 2,
    students: ['Wilson', 'Taylor']
  },
  {
    subject: "history",
    numberOfStudents: 4,
    students: ['Edith', 'Jacob', 'Peter', 'Betty']
  }
]

let courseStudents = courses.map(course => course.students)
// [
// [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ],
// [ 'Wilson', 'Taylor' ],
// [ 'Edith', 'Jacob', 'Peter', 'Betty' ]
// ]

[].concat.apply([], courseStudents) // We have to use this method

Array.prototype.flat method came into being. It accepts an optional depth parameter.

 let courseStudents = [
  [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ],
  [ 'Wilson', 'Taylor' ],
  [ 'Edith', 'Jacob', 'Peter', 'Betty' ]
]

let flattenOneLevel = courseStudents.flat(1)
console.log(flattenOneLevel)
// [
// 'Janet',
// 'Martha',
// 'Bob',
// [ 'Phil', 'Candace' ],
// 'Wilson',
// 'Taylor',
// 'Edith',
// 'Jacob',
// 'Peter',
// 'Betty'
// ]

let flattenTwoLevels = courseStudents.flat(2)
console.log(flattenTwoLevels)
// [
// 'Janet', 'Martha',
// 'Bob', 'Phil',
// 'Candace', 'Wilson',
// 'Taylor', 'Edith',
// 'Jacob', 'Peter',
// 'Betty'
// ]

Note that if no parameters are specified, the default depth is 1. This is very important because in our example, this does not completely flatten the array.

 let courseStudents = [
  [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ],
  [ 'Wilson', 'Taylor' ],
  [ 'Edith', 'Jacob', 'Peter', 'Betty' ]
]

let defaultFlattened = courseStudents.flat()
console.log(defaultFlattened)
// [
// 'Janet',
// 'Martha',
// 'Bob',
// [ 'Phil', 'Candace' ],
// 'Wilson',
// 'Taylor',
// 'Edith',
// 'Jacob',
// 'Peter',
// 'Betty'
// ]

The reason for this design is that the function is not greedy by default and requires explicit instructions to run in this way. Infinity can be used as a parameter for cases where the depth is unknown and the intention is to completely flatten the array.

 let courseStudents = [
  [ 'Janet', 'Martha', 'Bob', [ 'Phil', 'Candace' ] ],
  [ 'Wilson', 'Taylor' ],
  [ 'Edith', 'Jacob', 'Peter', 'Betty' ]
]

let alwaysFlattened = courseStudents.flat(Infinity)
console.log(alwaysFlattened)
// [
// 'Janet', 'Martha',
// 'Bob', 'Phil',
// 'Candace', 'Wilson',
// 'Taylor', 'Edith',
// 'Jacob', 'Peter',
// 'Betty'
// ]

As always, greedy operations should be used with caution, and if the depth of the array is indeed unknown, greedy operations may not be a good choice.

Array.prototype.flat method support situation

Chrome Firefox Safari Edge
75 67 12 Not supported
Chrome Android Firefox Android iOS Safari IE Mobile Samsung Internet Android Webview
75 67 12.1 Not supported Not supported 67

Array.prototype.flatMap method

With the addition of the flat method, we also get the combined function Array.prototype.flatMap . We've actually seen what it works in the example above, but let's look at one more.

If we wanted to insert elements into an array, what would it look like before ES2019 add these features?

 let grades = [78, 62, 80, 64]

let curved = grades.map(grade => [grade, grade 7])
// [ [ 78, 85 ], [ 62, 69 ], [ 80, 87 ], [ 64, 71 ] ]

let flatMapped = [].concat.apply([], curved) // Now flat, flat can be used but it did not exist before // [
// 78, 85, 62, 69,
// 80, 87, 64, 71
// ]

Now that we have Array.prototype.flat , we can improve this example a little bit.

 let grades = [78, 62, 80, 64]

let flatMapped = grades.map(grade => [grade, grade 7]).flat()
// [
// 78, 85, 62, 69,
// 80, 87, 64, 71
// ]

However, this is still a relatively popular pattern, especially in functional programming. So it's great to have it built into an array prototype. Using flatMap we can do this:

 let grades = [78, 62, 80, 64]

let flatMapped = grades.flatMap(grade => [grade, grade 7]);
// [
// 78, 85, 62, 69,
// 80, 87, 64, 71
// ]

Remember, the default parameter for Array.prototype.flat is 1. flatMap is equivalent to combining map and flat without parameters. Therefore, flatMap will only flatten one layer.

 let grades = [78, 62, 80, 64]

let flatMapped = grades.flatMap(grade => [grade, [grade 7]]);
// [
// 78, [ 85 ],
// 62, [ 69 ],
// 80, [ 87 ],
// 64, [ 71 ]
// ]

Array.prototype.flatMap method support situation

Chrome Firefox Safari Edge
75 67 12 Not supported
Chrome Android Firefox Android iOS Safari IE Mobile Samsung Internet Android Webview
75 67 12.1 Not supported Not supported 67

String.trimStart and String.trimEnd methods

Another nice addition to ES2019 is the alias, which makes some string function names more explicit. Previously, String.trimRight and String.trimLeft were available.

 let message = " Welcome to CS 101 "
message.trimRight()
// ' Welcome to CS 101'
message.trimLeft()
// 'Welcome to CS 101'
message.trimRight().trimLeft()
// 'Welcome to CS 101'

These are great functions, but it is also helpful to give them names that suit their purpose more. Delete the start and end spaces.

 let message = " Welcome to CS 101 "
message.trimEnd()
// ' Welcome to CS 101'
message.trimStart()
// 'Welcome to CS 101'
message.trimEnd().trimStart()
// 'Welcome to CS 101'

String.trimStart and String.trimEnd methods support situation

Chrome Firefox Safari Edge
75 67 12 Not supported

Optional catch binding

Another nice feature of ES2019 is to make the parameters in try-catch block optional. Previously, all catch blocks passed exceptions as parameters. This means that even if the code in catch block ignores it, it still exists.

 try {
  let parsed = JSON.parse(obj)
} catch(e) {
  // Ignore e, or use console.log(obj)
}

This is not the case anymore. If no exception is used in catch block, nothing is needed at all.

 try {
  let parsed = JSON.parse(obj)
} catch {
  console.log(obj)
}

This is a good option if you already know what the error is and are looking for the data that triggers it.

Support for optional catch binding

Chrome Firefox Safari Edge
75 67 12 Not supported

Changes to Function.toString() method

ES2019 also changed the way Function.toString() method runs. Previously, it completely removed spaces.

 function greeting() {
  const name = 'CSS Tricks'
  console.log(`hello from ${name}`)
}

greeting.toString()
//'function greeting() {\nconst name = \'CSS Tricks\'\nconsole.log(`hello from ${name} //`)\n}'

Now it reflects the true representation of the function in the source code.

 function greeting() {
  const name = 'CSS Tricks'
  console.log(`hello from ${name}`)
}

greeting.toString()
// 'function greeting() {\n'  
// " const name = 'CSS Tricks'\n"  
// ' console.log(`hello from ${name}`)\n'  
// '}'

This is mainly an internal change, but I can’t help thinking that this may make life easier for a blogger or two in the future.

Support of Function.toString() method

Chrome Firefox Safari Edge
75 60 12 – Partial support 17 – Partial support

This is the main new feature of ES2019!

You may also want to explore some other new features, including:

  • Symbol description
  • Sorting stability
  • ECMAScript as a superset of JSON
  • JSON.stringify

Have a happy JavaScript programming!

The above is the detailed content of All the New ES2019 Tips and Tricks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

See all articles