What you don't know about ES2023 | JD Cloud technical team

On June 27, the ECMA General Assembly approved the ECMAScript 2023 (es14) specification, which means that some new syntax will officially become the standard. Let's take a look at the new features of ECMAScript 2023 that deserve our attention.

Overview:

For specific details of the original text of the proposal, you can jump to: Completed Proposal

• Find the array from the back to the front

• Hashbang syntax

•Symbol type as key of WeakMap type

• New prototype methods that do not change the original array

Find array from back to front

In JavaScript, the existing Array.prototype.find() and Array.prototype.findIndex() two methods are the two most commonly used methods in array traversal. They are usually used to traverse to find items that meet the requirements in the array, but currently these two methods are traversed from front to back

const arr = [10, 20, 30, 40, 50];
arr.find(item => item > 30); // 40
arr.findIndex(item => item > 30); // 3

If you want to traverse from the back to the front, you have to reverse the array before, and then traverse the reversed array to find it. This is undoubtedly very counterintuitive. Two new arrays have been added to the standard this year. The traversal method Array.prototype.findLast() and Array.prototype.findLastIndex() , its function can also be seen from the name, the usage is exactly the same as find and findIndex , the only difference is that it traverses from the back to the front, applicable to arrays and class arrays

findLast(): returns the first found element, if not found, returnsundefined

findLastIndex(): Returns the index of the first found element, or if not found, returns-1

const arr = [10, 20, 30, 40, 50];
arr.findLast(item => item > 30); // 50
arr.findLastIndex(item => item > 30); // 4
arr.findLast(item => item > 50); // undefined
arr.findLastIndex(item => item > 50); // -1

Hashbang syntax

Hashbang comments are a special comment syntax that behaves (//) exactly like single-line comments, except that they #! start with , and are only valid at the very beginning of a script or module. Note that #! there cannot be any whitespace characters before the flag. A comment #! consists of all characters after that up to the end of the first line; only one such comment is allowed. A hashbang comment in JavaScript is similar to a shebang in Unix, providing a path to a specific JavaScript interpreter to use to execute the script.

// 写在脚本文件第一行
#!/usr/bin/env node
'use strict';
console.log(1);


// 写在模块文件第一行
#!/usr/bin/env node
export {};
console.log(1);

This allows you to run the script code directly

# 以前执行脚本
node demo.js


# 有了 hashbang 之后执行脚本
./demo.js

Hashbang syntax is only semantically meaningful when the script is run directly in the shell, otherwise the JavaScript interpreter treats it as a normal comment.

Symbol type as key of WeakMap type

Previously, the WeakMap type only allowed the use of objects as keys. This is a limitation of WeakMap. The new standard extends the WeakMap API to allow the use of unique Symbol types as keys. This makes it easier to create and share keys.

const weakMap = new WeakMap();


// 更具象征意义的key
const key = Symbol('my ref');
const someObject = { /* data */ };


weakMap.set(key, someObject)

In addition, the standard also solves another problem introduced in the Stage 2 proposal tuples and records : how to refer to and access non-primitive values ​​​​in primitive data types? In the tuple and record proposal, tuple and record types cannot contain objects, functions, and methods, and a TypeError exception will be thrown when doing so.

const server = #{
  port: 8080,
  handler: function (req) { /* ... */ } // TypeError
}

This limitation exists because one of the key goals of the tuple and record proposal is to guarantee deep immutability and structural equality of data by default. Accepting Symbol values ​​as WeakMap keys will allow JavaScript libraries to implement their own RefCollection-like thing that can be reused without leaking memory over time.

class RefBookkeeper {
  #references = new WeakMap();
  ref(obj) {
    const sym = Symbol();
    this.#references.set(sym, obj);
  }
  deref(sym) { return this.#references.get(sym); }
}
globalThis.refs = new RefBookkeeper();


const server = #{
  port: 8080,
  handler: refs.ref(function (req) { /* ... */ })
}
refs.deref(server.handler)({ /* ... */})

New prototype method that does not change the original array

This time the standard adds 4 new prototype methods that do not change the original array:

Array.prototype.toReversed() -> Array

Array.prototype.toSorted(compareFn) -> Array

Array.prototype.toSpliced(start, deleteCount, ...items) -> Array

Array.prototype.with(index, value) -> Array

In JavaScript, most of the methods in the array are non-destructive and will not change the original array, such as filter() the method

const arr = ['a', 'b', 'b', 'c'];
const result = arr.filter(x => x !== 'b');
console.log(result); // ['a', 'c']

Of course, there are also some methods that change the original array, such as **sort()**method

const arr = ['c', 'a', 'b'];
const result = arr.sort();
console.log(result); // ['a', 'b', 'c']

Among array methods, the following methods are destructive:

reverse()

sort()

splice()

If we want to use these array methods without changing the original array, we need to create a copy of the original array first, and then use these methods on the copy of the array. Therefore, non-destructive versions of these three methods are introduced, and there is no need to create a copy of the array to operate.

Besides that, there is a new non-destructive method: with(index, value). This method replaces the array element at the given parameter index in a non-destructive manner, ie a arr[index] = value non-destructive version of .

// toReversed()
const arr = ['a', 'b', 'c'];
const result = arr.toReversed();
console.log(result); // ['c', 'b', 'a']
console.log(arr);    // ['a', 'b', 'c']


// toSorted()
const arr = ['c', 'a', 'b'];
const result = arr.toSorted();
console.log(result);  // ['a', 'b', 'c']
console.log(arr);     // ['c', 'a', 'b']


// toSpliced()
const arr = ['a', 'b', 'c', 'd'];
const result = arr.toSpliced(1, 2, 'X');
console.log(result); // ['a', 'X', 'd']
console.log(arr);    // ['a', 'b', 'c', 'd'], 无法再得到已经删除的元素


// with()
const arr = ['a', 'b', 'c'];
const result = arr.with(1, 'X');
console.log(result);  // ['a', 'X', 'c']
console.log(arr);     // ['a', 'b', 'c

These methods apply to all arrays and also to TypedArray. In the tuple proposal mentioned above, these methods are also applicable. Tuples are equivalent to immutable arrays, so tuples do not support destructive methods, and these destructive methods are introduced into non-destructive versions for tuples is very helpful.

End

The above are ES2023 all standardized proposals. At present, the Chrome browser has fully supported them, and you can try new features in the debugging tool.

Author: JD Retail Xie Tian

Source: JD Cloud Developer Community

Clarification about MyBatis-Flex plagiarizing MyBatis-Plus Arc browser officially released 1.0, claiming to be a substitute for Chrome OpenAI officially launched Android version ChatGPT VS Code optimized name obfuscation compression, reduced built-in JS by 20%! LK-99: The first room temperature and pressure superconductor? Musk "purchased for zero yuan" and robbed the @x Twitter account. The Python Steering Committee plans to accept the PEP 703 proposal, making the global interpreter lock optional . The number of visits to the system's open source and free packet capture software Stack Overflow has dropped significantly, and Musk said it has been replaced by LLM
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10091800