Gets the key-value pair of an object
Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
const user = {
name: 'Klaus'.age: 23
}
// The argument types of the following three methods are iterables
console.log(Object.keys(user)) // => [ 'name', 'age' ]
console.log(Object.values(user)) // => [ 'Klaus', 23 ]
// entry --> [key, value]
// entrie --> [[key, value], [key, value]]
console.log(Object.entries(user)) // => [ [ 'name', 'Klaus' ], [ 'age', 23 ] ]
const friends = ['Alex'.'Klaus'.'Steven']
console.log(Object.keys(friends)) // => ['0', '1', '2']
console.log(Object.values(friends)) // => [ 'Alex', 'Klaus', 'Steven' ]
console.log(Object.entries(friends)) // => [ [ '0', 'Alex' ], [ '1', 'Klaus' ], [ '2', 'Steven' ] ]
const str = 'Alex'
console.log(Object.keys(str)) // => ['0', '1', '2', '3']
console.log(Object.values(str)) // => [ 'A', 'l', 'e', 'x' ]
console.log(Object.entries(str)) // => [ [ '0', 'A' ], [ '1', 'l' ], [ '2', 'e' ], [ '3', 'x' ] ]
Copy the code
String Padding
In ES8, padStart and padEnd methods are added, especially to fill the beginning and end of a string
const str = 'Hello World'
// padStart(before string), padEnd(after string)
// Argument 1 --> the length of the filled string
// Parameter 2 --> what to fill in (default space)
console.log(str.padStart(15.The '*')) // => ****Hello World
console.log(str.padEnd(15.The '-')) // => Hello World----
Copy the code
const str = 'Hello World'
// If the string length is shorter than the original string after padding
// The length of the filled string is equal to the length of the original string
// The fill is invalid
console.log(str.padStart(5.The '*')) // => Hello World
console.log(str.padEnd(5.The '-')) // => Hello World
Copy the code
Trailing Commas
Before ES5, you could not put an extra comma at the end of a function argument or parameter
// From ES8, however, an extra comma is added to the end of a function argument or parameter, which the JS engine can normally recognize and parse
function fun(a, b,) {
}
fun(a, b,)
Copy the code
Object spread operator
const obj = {
name: 'Klaus'.age: 23
}
console.log({... obj})// => { name: 'Klaus', age: 23 }
console.log({... obj} === obj)// => false
Copy the code
flat
flat
The Flat () method recurses through the array at a specified depth and merges all the elements with the elements in the traversed subarray into a new array.
const arr = ['key'.'value'['Hello'.'World'], [['name'.'Klaus'], ['age'.18]]]
// The flat argument is to be reduced in several dimensions -- the default value is 1
// If the dimension exceeds the maximum that can be flattened -- the maximum that can be flattened is processed
console.log(arr.flat())
/* => [ 'key', 'value', 'Hello', 'World', [ 'name', 'Klaus' ], [ 'age', 18 ] ] */
console.log(arr.flat(2))
/* => [ 'key', 'value', 'Hello', 'World', 'name', 'Klaus', 'age', 18 ] */
Copy the code
flatMap
The flatMap() method first maps each element using a mapping function and then compresses the result into a new array.
- FlatMap Indicates that the map operation is performed before the flat operation
- Flat in a flatMap is equivalent to a depth of 1 –> that is, flatMap can only flatten dimension 1, and cannot manually specify the flatten dimension
const message = ['Hello World'.'Hello Message'.'Hello React']
// console.log(message.map(item => item.split(' ')).flat())
/ / equivalent to the
console.log(message.flatMap(item= > item.split(' ')))
Copy the code
fromEntries
const user = {
name: 'Klaus'.age: 18
}
// fromEntries is the inverse operation of entries
const entries = Object.entries(user)
console.log(Object.fromEntries(entries)) // => { name: 'Klaus', age: 18 }
Copy the code
const str = 'name=klaus&age=23&height=18'
// New URLSearchParams(queryString) returns an entries object
const params = new URLSearchParams(str)
for (const entry of params) {
console.log(entry)
}
console.log(Object.fromEntries(params)) // => { name: 'klaus', age: '23', height: '18' }
Copy the code
Remove the blank space
const str = ' Hello World '
console.log(str.trim()) // => 'Hello World'
console.log(str.trimStart()) // => 'Hello World '
console.log(str.trimEnd()) // => ' Hello World'
Copy the code
BigInt
In the early days of JavaScript, we didn’t necessarily represent large numbers correctly
// Get the largest integer that can be represented
console.log(Number.MAX_SAFE_INTEGER)
Copy the code
In ES11, a new data type, BigInt, was introduced to represent large integers
// BigInt is represented by a number followed by n
const bigInt = 9007199254740991n
// Note: BigInt cannot be mixed with Number (other data types can).
// console.log(bigInt + 11) // => error
// console.log(bigInt + 11.5) // => error
console.log(bigInt + 'ww') // => 9007199254740991ww
// BigInt outputs values with n at the end to distinguish them
console.log(bigInt + 11n) // => 9007199254741002n
The BigInt method converts a common numeric type to BigInt
// The arguments to the BigInt method can only be integer values or corresponding strings
// BigInt cannot convert a Number value, even if it is a floating point Number value
console.log(BigInt(22)) // => 22n
console.log(BigInt('22')) // => 22n
// console.log(BigInt(12.5)) // => error
Log (BigInt('22.5')) // => error
// console.log(BigInt('ww')) // => error
// We can use the Number method to convert BigInt data to a normal Number type
// However, JS cannot use Number to represent large integers
// Therefore, the accuracy of the converted values cannot be guaranteed
console.log(Number(bigInt)) / / = > 9007199254740991
Copy the code
Null-value merge operator
// The common way to represent default values in ES5
console.log(undefined || 'default') // => default
console.log(null || 'default') // => default
// However, the following cases should not be the default values, but are judged as the default values
console.log(0 || 'default') // => default
console.log(' ' || 'default') // => default
console.log(false || 'default') // => default
// So, the way ES5 really represents default values is
const foo = 0
const res = [null.undefined].includes(foo) ? 'default' : foo
Copy the code
ES11 provides the Nullish Coalescing Operator, but this is too cumbersome to write.
console.log(undefined ?? 'default') // => default
console.log(null ?? 'default') // => default
console.log(0 ?? 'default') / / = > 0
console.log(' ' ?? 'default') / / = > '
console.log(false ?? 'default') // => false
Copy the code
Optional Chaining
Optional chains are also a new feature in ES11 that makes our code clearer and more concise when nulling and undefined
const obj = {
name: 'Alex'
}
/ / if? The name attribute is not returned. The link is broken and undefined is returned
console.log(null? .name)// => undefined
console.log(undefined? .name)// => undefined
console.log(0? .name)// => undefined
console.log(obj? .name)// => Alex
Copy the code
const users = [
{
name: 'Alex'}]// The optional chain operator can also be used on array elements
console.log(users? .0]? .name)// => Alex
console.log(users? .1]? .name)// => undefined
Copy the code
const Alex = {
name: 'Alex'.firend: {
name: 'Jhon'}}const Klaus = {
name: 'Klaus'
}
// Prints out the friend property for a user
function printFriend(user) {
if (user && user.firend && user.friend.name) {
console.log(user.firend)
}
}
Copy the code
const Alex = {
name: 'Alex'.firend: {
name: 'Jhon'}}const Klaus = {
name: 'Klaus'
}
function printFriend(user) {
// Optional chain operator
console.log(user? .firend? .name) }Copy the code
const Alex = {
name: 'Alex'.firend: {
name: 'Jhon'}}const Klaus = {
name: 'Klaus'
}
console.log(Klaus? .firend? .name)// => undefined
console.log(Alex? .firend? .name)// => Jhon
Copy the code
globalThis
Before ES11, get all objects in different running environments of JS, and get different results
- This and window can be obtained in the browser
- In Node we get it from global
So in ES11, globalThis is provided for fetching, which is a uniform specification
// In browser, return window
// In node, return global
console.log(globalThis)
Copy the code
FinalizationRegistry
The FinalizationRegistry object allows you to perform a callback when an object is garbage collected, which is commonly referred to as the Finalizer method
FinalizationRegistry provides a way for callback functions passed in FinalizationRegistry to be automatically executed when an object registered in the registry is reclaimed
You can register any object you want to clean up the callback by calling the Register method, passing in the object and its value.
// PS: You are advised to run the following cases in a browser
// 1. The browser environment has a separate JS process that is always running while browsing the page
// 2. In the Node environment, js scripts are actually executed, so a thread is started when js scripts are executed
// After the script is run, the node js process is actually closed, which is not convenient for testing
FinalizationRegistry is a class
The // argument is a callback function, the Registry function, that is executed when the registered variable is destroyed by GC
const finalRegistry = new FinalizationRegistry(val= > console.log(`${val}Being recycled))
let user = { name: 'Klaus' }
// Register variables that need to be listened on
// Parameter 1: the variable to be listened on
// Parameter 2: The key value of this variable in Registry, when destroyed by GC, is passed in as an argument when the Registry function is executed
finalRegistry.register(user, 'user')
// Set user to garbage
user = null
Copy the code
WeakRef
WeakRef can be used to manually create a weak reference
const user = { name: 'Klaus' }
// Create a weak reference to the variable pointed to by user
const ref = new WeakRef(user)
// Call deref to obtain the original value and then perform the corresponding operation
// 1. If the corresponding value is not destroyed, the corresponding value can be retrieved normally
// 2. If the value of deref has been destroyed by GC, the deref method returns undefined
console.log(ref.deref()?.name)
Copy the code
Logical merge operator
Logic merge operator (logical the assignment operators) is | | =, && =?? =
| | =
// ES5
let message = undefined
message = message || 'default value'
console.log(message) // default value
Copy the code
let message = undefined
message ||= 'default value'
console.log(message) // default value
Copy the code
?? =
// If the value is 0 or an empty string or false, we will trigger the corresponding default value if we use logic or judgment
// The null value merge operator appears
let message = 0
message = message ?? 'default value'
console.log(message) // 0
Copy the code
// ES12 provides a simplified version of the null-value merge operator
let message = 0message ?? ='default value'
console.log(message) // 0
Copy the code
&& =
// ES5
let user = {
name: 'Klaus'
}
user = user && user.name
console.log(user) // => Klaus
Copy the code
// ES6
let user = {
name: 'Klaus'
}
user &&= user.name
console.log(user) // => Klaus
Copy the code
Numeric Separator
Numeric Separator is just for the convenience of reading long numbers
There is no strict requirement for the exact number of bits to be partitioned
It’s just that normally, we’re going to do a three-digit split
const num = 123 _223_222_223_222_333
console.log(num)
const num1 = 12 _3223222223_222_333
console.log(num1)
Copy the code
replaceAll
const str = 'Hello World, Hello React'
console.log(str.replace('Hello'.'New')) // => New World, Hello React
console.log(str.replace(/Hello/g.'New')) // => New World, New React
console.log(str.replaceAll('Hello'.'New')) // => New World, New React
Copy the code