1. 解构赋值,合并对象
const username = { id: '@Taquiimam14' };
const website = { url: 'www.twitter.com' };
const social = { ...username, ...url };
// { id: '@Taquiimam14', url: 'www.twitter.com' }
2. 随机排序数组
function shuffleArr(array) {
return array.sort( () => Math.random( ) - 0.5) ;
}
let myArr = [1, 2, 3, 4, 5];
shuffleArr(myArr);
// [3, 1, 5, 4, 2]
3. Better 判断
// Old
if ( isSubscribed ) {
sendThankyouEmail();
}
// New
isSubscribed && sendThankyouEmail() ;
4. 动态属性名称
const dynamic = 'websites' ;
var social = {
userId: '@Taquiimam14',
[dynamic]: 'www.twitter.com'
};
// { userId: "@Taquiimam14", website: "www.twitter.com" }
5. 根据指定深度递归地将所有子数组元素拼接到新的数组中
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]
const arr2 = [0, 1, [2, [3, [4, 5]]]];
console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]
6. 调整数组大小
var array = [1, 2, 3, 4, 5];
array.length = 2 ;
// [1, 2]