在现代JavaScript编程中,ES6(ECMAScript 2015)引入了许多令人兴奋的新功能和语法,其中一些可能相对较冷门,但却非常实用。本文将深入探讨一些不太为人熟知却极具实际价值的高级技巧,为你展示如何利用这些功能提高代码的可读性和效率。
// 对象转为数组
const myObject = { a: 1, b: 2, c: 3 };
const entriesArray = Object.entries(myObject);
console.log(entriesArray);
// 输出: [['a', 1], ['b', 2], ['c', 3]]
// 数组转为对象
const newObj = Object.fromEntries(entriesArray);
console.log(newObj);
// 输出: { a: 1, b: 2, c: 3 }
const mySymbol = Symbol('description');
const myObject = {
[mySymbol]: 'This is a Symbol property'
};
console.log(myObject[mySymbol]);
// 输出: This is a Symbol property
let weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj));
// 输出: value
const promises = [
Promise.resolve('Resolved'),
Promise.reject('Rejected'),
Promise.resolve('Another Resolved')
];
Promise.allSettled(promises)
.then(results => console.log(results));
// 输出: [{status: "fulfilled", value: "Resolved"}, {status: "rejected", reason: "Rejected"}, {status: "fulfilled", value: "Another Resolved"}]
const bigNumber = 9007199254740991n + 1n;
console.log(bigNumber);
// 输出: 9007199254740992n
Array.of
用于创建具有可变参数的新数组。Array.from
用于将类数组对象或可迭代对象转换为数组。// 创建数组
const newArray1 = Array.of(1, 2, 3);
console.log(newArray1);
// 输出: [1, 2, 3]
// 从类数组对象创建数组
const arrayLike = { length: 3, 0: 'a', 1: 'b', 2: 'c' };
const newArray2 = Array.from(arrayLike);
console.log(newArray2);
// 输出: ['a', 'b', 'c']
Array.prototype.at
允许通过索引直接访问数组元素。Array.prototype.flat
用于将嵌套数组扁平化。// 直接访问数组元素
const myArray = ['a', 'b', 'c'];
console.log(myArray.at(1));
// 输出: b
// 嵌套数组扁平化
const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flattenedArray = nestedArray.flat(2);
console.log(flattenedArray);
// 输出: [1, 2, 3, 4, 5, 6]