您好,登录后才能下订单哦!
let
和 const
是 ES6 引入的两种新的变量声明方式,用于替代 var
。
let
声明的变量具有块级作用域。const
声明的变量是常量,一旦赋值后不能修改。let x = 10;
const y = 20;
箭头函数提供了一种更简洁的函数定义方式,并且不会绑定自己的 this
。
const add = (a, b) => a + b;
模板字符串允许在字符串中嵌入表达式,使用反引号(”)包裹。
const name = 'Alice';
const greeting = `Hello, ${name}!`;
解构赋值允许从数组或对象中提取值,并赋值给变量。
const [a, b] = [1, 2];
const { name, age } = { name: 'Alice', age: 25 };
函数参数可以设置默认值。
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
扩展运算符(...
)可以将数组或对象展开。
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
ES6 引入了 class
关键字,用于定义类。
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
ES6 引入了模块化语法,使用 import
和 export
。
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math.js';
Promise
用于处理异步操作。
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});
promise.then(result => console.log(result));
迭代器(Iterator
)和生成器(Generator
)用于处理集合的遍历。
function* generator() {
yield 1;
yield 2;
yield 3;
}
const iterator = generator();
console.log(iterator.next().value); // 1
Set
和 Map
是新的数据结构。
Set
是一组不重复的值。Map
是键值对的集合。const set = new Set([1, 2, 3]);
const map = new Map();
map.set('name', 'Alice');
Symbol
是一种新的原始数据类型,表示唯一的标识符。
const sym = Symbol('description');
Proxy
用于定义自定义行为,Reflect
提供了一组操作对象的方法。
const target = {};
const handler = {
get: (obj, prop) => prop in obj ? obj[prop] : 37
};
const proxy = new Proxy(target, handler);
尾调用优化允许在递归调用时避免栈溢出。
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
ES6 引入了新的数组方法,如 Array.from
、Array.of
、find
、findIndex
等。
const arr = Array.from('hello');
const found = arr.find(x => x === 'e');
ES6 引入了新的字符串方法,如 startsWith
、endsWith
、includes
等。
const str = 'hello';
console.log(str.startsWith('he')); // true
ES6 引入了新的对象方法,如 Object.assign
、Object.is
等。
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = Object.assign({}, obj1, obj2);
ES6 引入了新的数学方法,如 Math.trunc
、Math.sign
等。
console.log(Math.trunc(3.14)); // 3
ES6 引入了新的正则表达式特性,如 u
修饰符、y
修饰符等。
const regex = /hello/u;
ES6 引入了二进制和八进制字面量。
const binary = 0b1010;
const octal = 0o12;
ES6 允许在对象字面量中使用简写语法。
const name = 'Alice';
const obj = { name };
for...of
循环用于遍历可迭代对象。
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item);
}
ES6 引入了 async
和 await
,用于处理异步操作。
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
ES6 引入了新的数据结构,如 WeakMap
和 WeakSet
。
const weakMap = new WeakMap();
const weakSet = new WeakSet();
ES6 引入了新的 API,如 ArrayBuffer
、DataView
等。
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);
Array.prototype.includes
用于检查数组是否包含某个元素。
const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
ES7 引入了指数运算符(**
),用于计算幂。
const result = 2 ** 3; // 8
async
和 await
是 ES8 引入的语法糖,用于简化异步操作。
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
Object.values
和 Object.entries
用于获取对象的值和键值对。
const obj = { a: 1, b: 2 };
console.log(Object.values(obj)); // [1, 2]
console.log(Object.entries(obj)); // [['a', 1], ['b', 2]]
ES8 引入了 String.prototype.padStart
和 String.prototype.padEnd
,用于填充字符串。
const str = '5';
console.log(str.padStart(2, '0')); // '05'
Object.getOwnPropertyDescriptors
用于获取对象的所有属性描述符。
const obj = { a: 1 };
console.log(Object.getOwnPropertyDescriptors(obj));
ES8 引入了 SharedArrayBuffer
和 Atomics
,用于处理共享内存和原子操作。
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
Atomics.store(view, 0, 123);
ES9 引入了异步迭代器,允许在异步操作中使用 for-await-of
循环。
async function* asyncGenerator() {
yield 1;
yield 2;
yield 3;
}
(async () => {
for await (const value of asyncGenerator()) {
console.log(value);
}
})();
ES9 允许在对象中使用 ...
运算符进行解构和扩展。
const obj = { a: 1, b: 2 };
const { a, ...rest } = obj;
console.log(rest); // { b: 2 }
Promise.prototype.finally
允许在 Promise
完成后执行代码,无论成功或失败。
fetch('https://api.example.com/data')
.then(response => response.json())
.finally(() => console.log('Done'));
ES9 允许在正则表达式中使用命名捕获组。
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = regex.exec('2023-10-05');
console.log(match.groups.year); // 2023
ES9 引入了正则表达式的反向断言,允许在匹配时向前或向后查找。
const regex = /(?<=\$)\d+/;
const match = regex.exec('$100');
console.log(match[0]); // 100
ES9 引入了 s
修饰符,允许 .
匹配所有字符,包括换行符。
const regex = /hello.world/s;
console.log(regex.test('hello\nworld')); // true
ES9 允许在模板字符串中使用未转义的字符。
const str = String.raw`\u{61}`;
console.log(str); // \u{61}
Array.prototype.flat
用于将嵌套数组扁平化,Array.prototype.flatMap
用于先映射后扁平化。
const arr = [1, [2, [3]]];
console.log(arr.flat(2)); // [1, 2, 3]
Object.fromEntries
用于将键值对数组转换为对象。
const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 1, b: 2 }
String.prototype.trimStart
和 String.prototype.trimEnd
用于去除字符串开头和结尾的空白字符。
const str = ' hello ';
console.log(str.trimStart()); // 'hello '
console.log(str.trimEnd()); // ' hello'
Symbol.prototype.description
用于获取 Symbol
的描述。
const sym = Symbol('description');
console.log(sym.description); // 'description'
ES10 允许在 catch
语句中省略绑定。
try {
throw new Error('Oops');
} catch {
console.log('Error occurred');
}
ES10 允许在 JSON 字符串中使用未转义的字符。
const json = '"\u2028"';
console.log(JSON.parse(json)); // '\u2028'
ES10 修订了 Function.prototype.toString
,使其返回函数的完整源代码。
function foo() {}
console.log(foo.toString()); // 'function foo() {}'
可选链操作符(?.
)用于简化访问可能为 null
或 undefined
的属性。
const obj = { a: { b: 1 } };
console.log(obj.a?.b); // 1
console.log(obj.c?.d); // undefined
空值合并操作符(??
)用于在左侧值为 null
或 undefined
时返回右侧值。
const value = null ?? 'default';
console.log(value); // 'default'
BigInt
是一种新的数据类型,用于表示任意精度的整数。
const bigInt = 1234567890123456789012345678901234567890n;
console.log(bigInt + 1n); // 1234567890123456789012345678901234567891n
ES11 允许在运行时动态导入模块。
import('./module.js').then(module => {
module.default();
});
globalThis
提供了一种跨平台访问全局对象的方式。
console.log(globalThis === window); // true (in browser)
Promise.allSettled
用于等待所有 Promise
完成,无论成功或失败。
const promises = [Promise.resolve(1), Promise.reject(2)];
Promise.allSettled(promises).then(results => {
console.log(results);
});
String.prototype.matchAll
用于获取所有匹配的正则表达式结果。
const regex = /t(e)(st(\d?))/g;
const str = 'test1test2';
const matches = [...str.matchAll(regex)];
console.log(matches);
ES11 允许在模块中使用 export * as
语法。
export * as utils from './utils.js';
import.meta
提供了模块的元数据。
console.log(import.meta.url);
ES11 修订了 for-in
循环的机制,使其更加一致。
const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key);
}
ES12 引入了逻辑赋值操作符(&&=
、||=
、??=
)。
let x = 1;
x &&= 2; // x = 2
x ||= 3; // x = 2
x ??= 4; // x = 2
ES12 允许在数字中使用下划线(_
)作为分隔符。
const num = 1_000_000;
console.log(num); // 1000000
Promise.any
用于等待第一个成功的 Promise
。
const promises = [Promise.reject(1), Promise.resolve(2)];
Promise.any(promises).then(result => {
console.log(result); // 2
});
WeakRef
用于创建弱引用,允许对象在不被引用时被垃圾回收。
const obj = { a: 1 };
const weakRef = new WeakRef(obj);
console.log(weakRef.deref()); // { a: 1 }
FinalizationRegistry
用于在对象被垃圾回收时执行回调。
const registry = new FinalizationRegistry(value => {
console.log(`Object with value ${value} was garbage collected`);
});
const obj = { a: 1 };
registry.register(obj, 'value');
String.prototype.replaceAll
用于替换字符串中的所有匹配项。
const str = 'hello world';
console.log(str.replaceAll('o', 'a')); // 'hella warld'
ES12 允许在类中定义私有方法和访问器。
class Person {
#privateMethod() {
console.log('Private method');
}
get #privateGetter() {
return 'Private getter';
}
}
ES12 允许在类中定义静态字段和方法。
class Person {
static staticField = 'Static field';
static staticMethod() {
console.log('Static method');
}
}
ES12 允许在模块的顶层使用 await
。
const data = await fetch('https://api.example.com/data');
console.log(data);
ES12 引入了新的正则表达式特性,如 d
修饰符。
const regex = /hello/d;
console.log(regex.exec('hello').indices);
ES12
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。