常用到的es6用法

mac2022-07-05  12

一、数据类型(let/const)

1、在其他语言(如C/C++/java等)中,变量最小作用域是以{}括起来的块级作用域,相对而言,在es5前,js中最小的作用域为函数,这样会导致在某些场景下,运用起来会比较繁琐。

举例子

1 for (var i = 0; i < 3; i++) { 2 setTimeout(function() { 3 console.log(i); 4 }, 0); 5 } 7 console.log(i);

执行结果:

5 //循环体外打印 5 5 5

我们原本期望通过循环和定时器能够依次打印0、1、2,但是由于通过var声明的变量的最小作用域为函数,导致函数体外的i最终污染了循环体中的i。当然我们可以通过函数来解决问题

解决办法:

for (var i = 0; i < 3; i++) { (function(i) { setTimeout(function(){ console.log(i); }, 0); })(i) } console.log(i);

这样借助自执行函数的方式可以解决,但是比较麻烦,es6中的let关键字,可以很容易的帮助我们解决该问题。

for (let j = 0; j < 3; j++) { setTimeout(function() { console.log(j); }, 0); } console.log(j);

这样在循环体外访问会报错 not define。let允许声明一个作用域被限制在块级作用域中的变量、语句或者表达式,而var只能声明在全局或者函数块的变量。

2、const关键字声明变量的作用域同let,不同点是,它是用于声明常量的关键字,声明时必须赋值,赋值后不能被变更,即只读。

二、字符串

1、模板字符串:允许嵌入表达式的字符串字面量。可以使用多行字符串和字符串插值功能。

//之前 console.log('hello \n world') //之后 console.log(`hello world`)//执行结果helloworldlet name = 'mili';let age = 23;console.log(`Hello, my name is ${name}, I am ${age}`);

2、includes(str, index):检测字符串中是否存在子串

3、startsWith(str, index):检测字符串是否以某子串开头

4、endsWith(str, index):检测字符串是否以某子串结尾

如果要查询某子串在字符串中的具体位置,可以使用indexOf

三、数组

在es5之前数组有些超好用的方法,如(map、filter、some、every等)都非常实用,具体细节此处就不做展开;

1、find():传入回调函数,找到数组中符合条件的第一个元素,并返回;

2、findIndex():传入回调函数,找到数组中符合条件的第一个元素的下标,并返回;

let objArr = [{name: 'a', age: 10},{name: 'b', age: 20},{name: 'c', age: 30}]; let dest = objArr.find((item) => {return item.age > 10;}); let destIndex = objArr.findIndex((item) => {return item.age > 10}); console.log(dest); console.log(destIndex);

输出结果:{name: "b", age: 20}

1

3、arr.fill(value, start, end):用新元素替换掉数组内的元素,可以指定替换的下标范围;

4、arr.copyWithin(target, start, end):选择数组的某个下标,从该位置开始复制元素,也可以指定复制的元素范围;

let fillArr = [1, 2, 3, 4, 5, 6]; fillArr.fill(7, 1, fillArr.length-1);const copyArr = [1, 2, 3, 4, 5];console.log(copyArr.copyWithin(3)) // [1,2,3,1,2] 从下标为3的元素开始,复制数组,所以4, 5被替 console.log(fillArr);console.log(copyArr);

输出结果:

[1, 7, 6]

[1, 2, 3, 1, 2]

四、函数

1、箭头函数:箭头函数没有自己的this(this来自父级最近的非箭头函数)、arguments、super或者new.target

普通函数涉及到this指针:1、函数座位全局函数被调用,this指向全局对象;2、函数座位对象的方法被调用,this指向对象;

let arr = [2, 10, 8, 20]; let newArr = arr.filter((item) => { return item > 8 }) console.log(newArr);

2、函数参数默认值

// es6前 function handle(num, callback) { num = num || 6; callback = callback || function (data) {console.log(data)}; callback(num); } // es6后 function handle(num = 6, callback = function (data) {console.log(data)}) { callback(num); }

五、其他

迭代器、promise与异步编程、proxy代理待更新

转载于:https://www.cnblogs.com/juntao-snail/p/9599261.html

最新回复(0)