ES6知识点

一、关于取值

const {a,b,c,d,e} = obj;
const f = a + d;
const g = c + e;

 

注:ES6的解构赋值虽然好用。但是要注意解构的对象不能为undefinednull。否则会报错,故要给被解构的对象一个默认值。

const {a,b,c,d,e} = obj || {};

二、关于合并数据

const a = [1,2,3];
const b = [1,5,6];
const c = [...new Set([...a,...b])];//[1,2,3,5,6]
const obj1 = {
  a:1,
}
const obj2 = {
  b:1,
}
const obj = {...obj1,...obj2};//{a:1,b:1}

三、关于拼接字符串

const name = '小明';
const score = 59;
const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;

四、关于if中判断条件

if(
    type == 1 ||
    type == 2 ||
    type == 3 ||
    type == 4 ||
){
   //...
}
优化为:
const condition = [1,2,3,4];
if( condition.includes(type) ){
   //...
}

五、关于列表搜索

const a = [1,2,3,4,5];
const result = a.find(item =>item === 3)

六、关于扁平化数组

const deps = {
'采购部':[1,2,3],
'人事部':[5,8,12],
'行政部':[5,14,79],
'运输部':[3,64,105],
}
let member = [];
for (let item in deps){
    const value = deps[item];
    if(Array.isArray(value)){
        member = [...member,...value]
    }
}
member = [...new Set(member)]
优化为:
const deps = {
    '采购部':[1,2,3],
    '人事部':[5,8,12],
    '行政部':[5,14,79],
    '运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);
//其中使用Infinity作为flat的参数,使得无需知道被扁平化的数组的维度。(flat方法不支持IE浏览器。)

七、关于获取对象属性值

const name = obj && obj.name;
优化为:
const name = obj?.name;

八、关于添加对象属性

let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';

九、关于输入框非空的判断

if(value !== null && value !== undefined && value !== ''){
    //...
}
优化为:
if((value??'') !== ''){
  //...
}
//非空判断 val??'-'

十、关于异步函数的吐槽

const fn1 = () =>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 300);
  });
}
const fn2 = () =>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(2);
    }, 600);
  });
}
const fn = () =>{
   fn1().then(res1 =>{
      console.log(res1);// 1
      fn2().then(res2 =>{
        console.log(res2)
      })
   })
}

优化为:
const fn = async () =>{
  const res1 = await fn1();
  const res2 = await fn2();
  console.log(res1);// 1
  console.log(res2);// 2
}
补充:
//要做并发请求时,还是要用到Promise.all()
//如果并发请求时,只要其中一个异步函数处理完成,就返回结果,要用到Promise.race()
const fn = () =>{
   Promise.all([fn1(),fn2()]).then(res =>{
       console.log(res);// [1,2]
   }) 
}

 十一:将Set对象转换为数组

  const set = new Set(['foo', 'bar', 'baz', 'foo']);
  Array.from(set);
  // [ "foo", "bar", "baz" ]

  <!-- 当然你也可以用ES6的简单写法 -->
  [ ... new Set(['foo', 'bar', 'baz', 'foo'])]

十二:将Map对象转换为数组

  const map = new Map([[1, 2], [2, 4], [4, 8]]);
  Array.from(map);
  // [[1, 2], [2, 4], [4, 8]]

  const mapper = new Map([['1', 'a'], ['2', 'b']]);
  Array.from(mapper.values());
  // ['a', 'b'];

  Array.from(mapper.keys());
  // ['1', '2'];

十三:将Element NodeList转换为数组

  // Create an array based on a property of DOM Elements
  const images = document.getElementsByTagName('img');
  const sources = Array.from(images, image => image.src);
  const insecureSources = sources.filter(link => link.startsWith('http://'));

  //这里的getElementsByTagName得到的images就是个类数组,同样我们可以很自然的想到通过querySelectorAll()得到的集合也是类数组

十四:将函数arguments转换为数组

  function f() {
    return Array.from(arguments);
  }
  f(1, 2, 3);

  // [ 1, 2, 3 ]

十五:填充数组

 <!-- 用索引填充 -->
  Array.from({length: 5}, (v, i) => i);
//[0, 1, 2, 3, 4]
  <!-- 用指定的值填充 -->
  Array.from({length: 5}, (v, i) => 6666);
//(5) [6666, 6666, 6666, 6666, 6666]
  <!-- 用指定的值填充 -->
  Array(10).fill(666);
  //(10) [666, 666, 666, 666, 666, 666, 666, 666, 666, 666]
  <!-- map填充会失效 -->
  Array(3).map((item,index)=>index);
  // 这个不会得到[0,1,2],而会得到[empty,empty,empty]
<!--将只有一个元素的组织快速复制n倍 -->
 var a = [3]
 var b = Array.from({length: 10}, (v, i) => a[0]);
//[3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

十六:克隆数组

 <!-- 一维度操作 -->
  var a = [1, 2, 3, [4, 5, 6]]
  var b = a
  var c = Array.from(a)
  a.push(7)
  // a: [1, 2, 3, [4, 5, 6], 7]
  // b: [1, 2, 3, [4, 5, 6], 7]
  // c: [1, 2, 3, [4, 5, 6]] //这个没有7

  <!-- 二维度操作 -->
  var a = [1, 2, 3, [4, 5, 6]]
  var b = a
  var c = Array.from(a)
  a[3].push(7)
  // a: [1, 2, 3, [4, 5, 6, 7]]
  // b: [1, 2, 3, [4, 5, 6, 7]]
  // c: [1, 2, 3, [4, 5, 6, 7]]

 十七、类数组和数组

数组具有length属性、不具有数组的方法

//类数组和数组的区分方法
var lei=document.getElementsByClassName("lei");
 var arr=[1,2,3,4];
// 1、利用instanceof
 console.log(lei instanceof Array);//false
 console.log(arr instanceof Array);//true

// 2、利用constructor
console.log(lei.constructor===Array);//false
console.log(arr.constructor===Array);//true

// 3、利用toString方法
console.log(Object.prototype.toString.call(lei));//[object HTMLCollection]
console.log(Object.prototype.toString.call(arr));//[object Array]
// tostring方法也常用来区分数组和对象
var object=new Object();
console.log(Object.prototype.toString.call(object));//[object Object]

// 4、isArray()
console.log(Array.isArray(lei));  //false
console.log(Array.isArray(arr));  //true

//类数组转换为数组
// 1、循环
var tranlei=[];
for(var i=0;i<lei.length;i++){
      tranlei.push(lei[i]);
}
console.log(tranlei);
 console.log(tranlei instanceof Array);//true
//2、slice()
var tranlei1=Array.prototype.slice.call(lei);
console.log(tranlei1);
console.log(tranlei1 instanceof Array);//true
//3、es6中的from(),第一个参数为要转化的类数组,第二个参数类似于map()可以对每个元素进行处理,将处理后的值放入返回的数组,Array.from()的另一个应用是,将字符串转为数组,然后返回字符串的长度
tranlei2=Array.from(lei,(s)=>{
console.log(s.innerHTML);
});
console.log(tranlei2 instanceof Array);//true
var str="123kkaklown";
console.log(Array.from(str).length); //11

 数组扁平化:已有多级嵌套数组 : [1, [2, [3, [4, 5]]], 6] 将其扁平化处理 输出: [1,2,3,4,5,6]

Es6字符串新增的方法
1、includes():返回布尔值,表示是否找到了参数字符串。
2、startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
3、endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
let str='Hello word!'
console.log(str.includes('o'));//true
console.log(str.startsWith('Hello'));//true
console.log(str.endsWith('!'));//true
4、repeat方法返回一个新字符串,表示将原字符串重复n次。
console.log('x'.repeat(3))//'xxx'
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana"参数如果是小数,会被取整。
5、padStart()用于头部补全,padEnd()用于尾部补全。
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
//如果原字符串的长度,等于或大于最大长度,则字符串补全不生效,返回原字符串。
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
'abc'.padStart(10, '0123456789')
// '0123456abc'
如果省略第二个参数,默认使用空格补全长度。

'x'.padStart(4) // '   x'
6、trim()消除首尾空格、trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。
7、替换replace  replaceAll
'aabbcc'.replace('b', '_')//'aa_bcc' 只能替换第一个匹配
'aabbcc'.replaceAll('b', '_')// 'aa__cc'替换所有匹配
8、at()方法接受一个整数作为参数,返回参数指定位置的字符,支持负索引(即倒数的位置)。
const str = 'hello';
str.at(1) // "e"
str.at(-1) // "o"
如果参数位置超出了字符串范围,at()返回undefined。
9、Math.trunc方法用于去除一个数的小数部分,返回整数部分。
对于空值和无法截取整数的值,返回NaN。
//Math.trunc(4.9) // 4
Math.trunc(-4.1) // -4

 

参考:https://juejin.cn/post/7016520448204603423
https://juejin.cn/post/7110608509523197989
posted @ 2022-07-11 16:43  dongxiaolei  阅读(22)  评论(0编辑  收藏  举报