小笔记-ES6、7、8、10

197 阅读6分钟

ES6

一、数组随机排序(打乱顺序)

let arr=['1天','娃哈哈','西八儿',true,false,'dddddd']
arr=arr.sort(()=>0.5-Math.random())
console.log(arr) 
//['dddddd', true, '娃哈哈', '西八儿', false, '1天'] 每次都是随机

二、去除除数字之外的所有字符

let str='adsfadsfasf asfdasf %^0123()LLmfsd45{}{67}d  saf89'
let nums=str.replace(/\D/g,'')
console.log(nums)
// 0123456789

三、反转字符串或者单词

let sentence='this is my work, you know?'
let reverseSentence=reverseBySeparator(sentence,'')
console.log(reverseSentence)    // ?wonk uoy ,krow ym si sihtlet reverseEachWord=reverseBySeparator(reverseSentence,' ')
console.log(reverseEachWord)    // siht si ym ,krow uoy ?wonk
​
  
function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator);
}

四、将数字从十进制转换为二进制或十六进制

let number=42
let binaryNumber=number.toString(2)
let hexadecimalNumber=number.toString(16)
console.log(binaryNumber)   // 101010
console.log(hexadecimalNumber)  // 2aNumberObject.toString(radix);
//  radix为可选。规定表示数字的基数,使 2 ~ 36 之间的整数。若省略该参数,则使用基数 10。但是要注意,如果该参数是 10 以外的其他值,则 ECMAScript 标准允许实现返回任意值。//  二进制转十进制
let num='11'
console.log(parseInt(num, 2);) //3parseInt(string, radix);
//  string为必需。要被解析的字符串。radix为可选。表示要解析的数字的基数。该值介于 2 ~ 36 之间。如果省略该参数或其值为 0,则数字将以 10 为基础来解析。如果它以 “0x” 或 “0X” 开头,将以 16 为基数。如果该参数小于 2 或者大于 36,则parseInt() 将返回 NaN。

五、合并多个对象

let obj1={
  a:1,
  b:2
}
let obj2={
  c:3,
  d:4
}
let merge={...obj1,...obj2}
console.log(merge)  // {a: 1, b: 2, c: 3, d: 4}

六、== 与 ===

//  ==  类型转换(浅比较)
//  ===  无类型转换(严格比较)console.log(0==false)   // true
console.log(0===false)  // false
console.log(1=='1') // true
console.log(1==="1")    // false
console.log(null==undefined)    // true
console.log(null===undefined)   // false

七、解构赋值

let forest={
    a:'aaa',
    b:2,
    c:{
        e:'eee',
        f:true,
        g:4
    },
    h:['h111','h222','h333']
}
let {a,b,c,h}=forest
let {e,f,g}=c
let [h111,h222,h333]=h
console.log(a,b,e,f,g,h111,h222,h333)   // aaa 2 eee true 4 h111 h222 h333

八、交换变量的值

let a='aaa';
let b='bbb';
[a,b]=[b,a]
console.log(a,b)    // bbb aaa

九、回文字符串

let isReverse=(str)=>{
    let revStr=str.split('').reverse().join('')
    return str==revStr
}
console.log(isReverse('abc'))	//	false
console.log(isReverse('aba'))	//	true

十、三目运算符

let a=10
let b=(a<10)?'low':'high'
console.log(b)	//	high

十一、随机值

let element=['1天','娃哈哈','西八儿',true,false,'dddddd']
let random=(arr)=> arr[Math.floor(Math.random()*arr.length)]
console.log(random(element))	//	随机一个数组中的值

十二、冻结对象

let obj={
    a:1,
    b:'bbb'
}
Object.freeze(obj)	//冻结对象
console.log(obj.a)	//	1
obj.a=2	// 被冻结的对象不会在被修改
console.log(obj.a)	//	1

十三、数组去重

let ele=['1天','娃哈哈','西八儿',true,false,'dddddd',true,false,'2天','1天']
let distinct=(arr)=>[...new Set(arr)]
console.log(distinct(ele))	//	 ['1天', '娃哈哈', '西八儿', true, false, 'dddddd', '2天']

十四、保留指定位小数

let num=0.157212
console.log(num.toFixed(2))	//	0.16
console.log(num.toFixed(3))	//	0.157

十五、清空数组

let arr=[1,2,3,4,5,6]
console.log(arr)	//	[1,2,3,4,5,6]
arr.length=0	//	清空数组,修改原数组本身
console.log(arr)	// 	[]

十六、RGB转换为HEX

let tgbToHex=(r,g,b)=>{
    let toHex=(num)=>{
        let hex=num.toString(16)
        return hex.length==1?`0${hex}`:hex
    }
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
console.log(tgbToHex(255,255,255))	//	#ffffff
console.log(tgbToHex(0,0,0))	//	#000000
console.log(tgbToHex(46,52,67))		//	#2e3443

十七、数组获取最大最小值

let arr=[1,2,5,8,1,2,42,12,89,232,64,32,1223,56]
let max=Math.max(...arr)
let min=Math.min(...arr)
console.log(max)	//	1223
console.log(min)	//	1

十八、空值合并运算符

let a
let b=1
let c=null
let d=''

let aa=a??'aa'
let bb=b??'bb'
let cc=c??'cc'
let dd=d??'dd'

console.log(aa,bb,cc,dd)	//	aa 1 cc ''

//空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

十九、过滤掉数组中值为false的值

let nums=[1,0,null,undefined,false]
let filter=nums.filter(Boolean)
console.log(filter)	//	[1]

ES7

一、includes

// indexOf方法
let list = ['a', 'b', 'c', NaN]
 
if(list.indexOf(NaN) !== -1) {
  console.log('包含----->>>')  // 控制台并没有打印
}
// includes方法
let list = ['a', 'b', 'c', NaN]
 
if(list.includes(NaN)) {
  console.log('包含')  // 包含
}

二、**指数运算符

// 在之前我们会通过 Math.pow() 来进行指数的运算 
let pow = Math.pow(2, 3)
console.log(pow) //8

// 现在可以使用 ** 来替代
let pow = 2 ** 3
console.log(pow) //8

ES8

一、Object.values()

const obj = {
  name: 'wft',
  age: 18
}
 
console.log(Object.keys(obj)) // [ 'name', 'age' ]
console.log(Object.values(obj)) // [ 'wft', 18 ]
 
/**
 * 很少用
 */
// 传入数组
console.log(Object.keys([1, 2, 3])) // [ '0', '1', '2' ]
console.log(Object.values([1, 2, 3])) // [ 1, 2, 3 ]
// 传入字符串
console.log(Object.keys('abc')) // [ '0', '1', '2' ]
console.log(Object.values('abc')) // [ 'a', 'b', 'c' ]

二、Object.entries()

entries()方法 返回一个给定对象自身可枚举属性的键值对数组,其排列与使用for...in 循环遍历该对象时返回的顺序一致(区别在于for...in循环也枚举原型链中的属性)

简单说就是Object.entries()可以把一个对象的键值以数组的形式遍历出来,结果和for...in一致,但不会遍历原型属性

const obj = {
  name: 'wft',
  age: 18
}
 
let objEntries = Object.entries(obj)
console.log(objEntries) // [ [ 'name', 'wft' ], [ 'age', 18 ] ]
 
for(let [key, val] of objEntries) {
  console.log(key, '----->>>')
  console.log(val, '----->>>')
}

三、String Padding:padStart 和 padEnd

两个字符串的方法,参数一样。分别对字符串进行首尾填充

接受两个参数

第一个参数:传入要填充到的长度是几

第二个参数: 选择用什么填充

let message = 'Hello World'
 
// 将message从前面用 * 填充至长度15,然后再从后面用 - 填充至长度20
let newMessage = message.padStart(15, '*').padEnd(20, '-')
 
console.log(newMessage) //****Hello World-----

四、Trailing-Commas(结尾的逗号)使用 (做个了解就好)

这个怎么说呢,,就是在ES8之前我们函数的最后一个参数后面是不能有逗号的,是不允许的,直接会报错,但是ES8之后,有了这么个语法,就可以加了,就像下面的例子

function fn(m, n,) {
 
}
 
fn(1, 2,)

五、Object.getOwnPropertyDescriptors() (了解一下好了)

获取所有属性的描述符

let obj = {
  name: 'wft',
  age: 18
}
 
console.log(Object.getOwnPropertyDescriptors(obj))
// {
//   name: {
//     value: 'wft',
//     writable: true,
//     enumerable: true,
//     configurable: true
//   },
//   age: { value: 18, writable: true, enumerable: true, configurable: true }
// }

ES10

一、flat

扁平数组,对数组进行降维

/**
 *  Array - arr.flat(<depth>) 扁平化多维数组
 *  1. 可选参数:depth  指定要提取嵌套数组的结构深度,默认值为 1。
 *  2. 返回值:一个包含将数组与子数组中所有元素的新数组
 *  3. depth 设置为 Infinity 无限扁平
 */
let arr = [1, 2, 3, [4, 5], [6, 7, [8, 9]], 10, 11]
 
arr.flat() // [ 1, 2, 3, 4, 5, 6, 7, [ 8, 9 ], 10, 11 ]
arr.flat(2) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr.flat(Infinity) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

二、flatMap

和数组的map方法,有点儿像,但也有点儿差距, 如果里面有数组的话,flatMap会自动降一个维度(注意是一个维度!)

let infos = [ "Hello World", "你好啊 李银河!", "My name is WFT"]
 
//  map 使用
let target1 = infos.map(item => item.split(" "))  // [ [ 'Hello', 'World' ], [ '你好啊', '李银河!' ], [ 'My', 'name', 'is', 'WFT' ] ]
 
// flatMap 使用
let target2 = infos.flatMap(item => item.split(" ")) // [ 'Hello', 'World', '你好啊', '李银河!', 'My', 'name', 'is', 'WFT' ]

三、Object.fromEntries()

ES8说了 Object.entries() , Object.fromEntries()就是将Object.entries()再转回去

let obj = {
  name: 'wft',
  age: 18
}
 
let entries = Object.entries(obj) // [ [ 'name', 'wft' ], [ 'age', 18 ] ]
 
let fromEntries = Object.fromEntries(entries) // { name: 'wft', age: 18 }

四、trimStart 和 trimEnd

之前有个 trim() 方法,是去掉字符串首尾空格,现在 trimStart 就是去除前面的空格,trimEnd去除后面的空格,使用起来也很简单

const message = "   Hellow World   "
 
console.log(message.trimStart())
console.log(message.trimEnd())