1 、标记模板文字
let price = 10 ;
console. log ( highlight` The price is ${ price} dollars. ` ) ;
2、使用 Object.entries() 和 Object.fromEntries()
let person = { name : "Alice" , age : 25 } ;
let entries = Object. entries ( person) ;
let newPerson = Object. fromEntries ( entries) ;
3、用于唯一元素的 Set 对象
let numbers = [ 1 , 1 , 2 , 3 , 4 , 4 ] ;
let uniqueNumbers = [ ... new Set ( numbers) ] ;
4、对象中的动态属性名称
let dynamicKey = 'name' ;
let person = { [ dynamicKey] : "Alice" } ;
5、使用 bind() 进行函数柯里化
function multiply ( a, b ) {
return a * b;
}
let double = multiply . bind ( null , 2 ) ;
console. log ( double ( 5 ) ) ;
6、使用 Array.from() 从类似数组的对象创建数组
let nodeList = document. querySelectorAll ( 'div' ) ;
let nodeArray = Array. from ( nodeList) ;
7、可迭代对象的 for…of 循环
for ( let value of [ 'a' , 'b' , 'c' ] ) {
console. log ( value) ;
}
8、使用 Promise.all() 实现并发 Promise
let promises = [ fetch ( url1) , fetch ( url2) ] ;
Promise. all ( promises)
. then ( responses => console. log ( 'All done' ) ) ;
9、函数参数的 Rest 参数
function sum ( ... nums) {
return nums. reduce ( ( acc, current ) => acc + current, 0 ) ;
}
10、用于性能优化的记忆化
const memoize = ( fn ) => {
const cache = { } ;
return ( ... args) => {
let n = args[ 0 ] ;
if ( n in cache) {
console. log ( 'Fetching from cache' ) ;
return cache[ n] ;
} else {
console. log ( 'Calculating result' ) ;
let result = fn ( n) ;
cache[ n] = result;
return result;
}
} ;
} ;
11、使用 ^ 交换值
let a = 1 , b = 2 ;
a ^= b; b ^= a; a ^= b;
12、使用 flat() 展平数组
let nestedArray = [ 1 , [ 2 , [ 3 , [ 4 ] ] ] ] ;
let flatArray = nestedArray. flat ( Infinity ) ;
13、使用一元加法转换为数字
let str = "123" ;
let num = + str;
14、HTML 片段的模板字符串
let items = [ 'apple' , 'orange' , 'banana' ] ;
let html = ` <ul> ${ items. map ( item => ` <li> ${ item} </li> ` ) . join ( '' ) } </ul> ` ;
15、使用 Object.assign() 合并对象
let items = [ 'apple' , 'orange' , 'banana' ] ;
let html = ` <ul> ${ items. map ( item => ` <li> ${ item} </li> ` ) . join ( '' ) } </ul> ` ;
16、短路默认值
let options = userOptions || defaultOptions;
17、使用括号表示法动态访问对象属性
let book = "name" ;
let value = book[ property] ;
18、使用 Array.includes() 进行存在性检查
if ( myArray. includes ( "value" ) ) {
}
19、Function.prototype.bind() 的强大功能
const greet = function ( greeting, punctuation ) {
return ` ${ greeting} , ${ this . name} ${ punctuation} ` ;
} ;
const greetJohn = greet . bind ( { name : 'John' } , 'Hello' ) ;
console. log ( greetJohn ( '!' ) ) ;
20、防止对象修改
let obj = { name : "Immutable" } ;
Object. freeze ( obj) ;
obj. name = "Mutable" ;