欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > ES6新增特性

ES6新增特性

2024/10/24 1:48:15 来源:https://blog.csdn.net/m0_62359005/article/details/142985667  浏览:    关键词:ES6新增特性

ES6又称ECMAScript6、ECMAScript2015

新特性:

1. 块级作用域:let const ,不会有变量提示、块级作用域的内容、不能在同一个作用域重复声明

2. Promise:解决了回调地狱

3. 箭头函数:

4. 定义类语法糖:Class

5.解构赋值

解构赋值是一种表达式,它允许我们将数组或对象的值解压到不同的变量中。在ES6中,我们可以使用这种特性来简化我们的代码,并使其更具可读性。

以下是一些使用ES6解构赋值的示例:

数组解构:

let [a, b, c] = [1, 2, 3];

console.log(a); // 1

console.log(b); // 2

console.log(c); // 3

对象解构:

let {x, y} = {x: 1, y: 2};

console.log(x); // 1

console.log(y); // 2

嵌套对象解构:

let {loc: {x, y}} = {loc: {x: 1, y: 2}};

console.log(x); // 1

console.log(y); // 2

默认值:

let [a, b = 2] = [1];

console.log(a); // 1

console.log(b); // 2

函数参数解构:

function add([a, b]){

return a + b;

}

console.log(add([1, 2])); // 3

交换变量的值:

let a = 1;

let b = 2;

[a, b] = [b, a];

console.log(a); // 2

console.log(b); // 1

6.扩展运算符

7. 增加基本数据类型:Symbol,表示独一无二的值

8. 新增了函数参数的默认值

9. 数组新增API

a. Array.from(): 用于将类数组对象或可迭代对象转换为数组。

const arrayLike = {0: 'a', 1: 'b', 2: 'c', length: 3};

const arr = Array.from(arrayLike); // ['a', 'b', 'c']

b. find(): 返回数组中满足提供的测试函数的第一个元素的值。若没有找到返回undefined

const numbers = [1, 2, 3, 4, 5];

const found = numbers.find(num => num > 3); // 4

c. findIndex(): 返回数组中满足提供的测试函数的第一个元素的索引。若没有找到返回-1

const numbers = [1, 2, 3, 4, 5];

const index = numbers.findIndex(num => num > 3); // 3

d. fill(): 用一个固定值填充整个数组或数组的一部分。

const arr = new Array(5).fill(1); // [1, 1, 1, 1, 1]

e. entries()keys(),和values(): 分别返回迭代器,可以用于遍历数组的索引、键和值。for (const [index, value] of arr.entries()) {

console.log(index, value);

}

f.includes(): 判断数组是否包含指定的元素,返回布尔值。

const numbers = [1, 2, 3];

const includes = numbers.includes(2); // true

g. flat() 和 flatMap(): 用于扁平化数组。flat()可以将数组扁平化,flatMap()在扁平化的同时还可以执行映射操作。

const arr = [1, [2, [3]]];

const flatArr = arr.flat(); // [1, 2, [3]]

const flatMapArr = arr.flatMap(x => [x, x * 2]); // [1, 2, 2, 4]

h. filter(): 创建一个新数组,包含通过测试的所有元素。

const numbers = [1, 2, 3, 4, 5];

const filtered = numbers.filter(num => num > 3); // [4, 5]

i. map(): 创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。

const numbers = [1, 2, 3];

const mapped = numbers.map(num => num * 2); // [2, 4, 6]

j. reduce() 和 reduceRight(): 对数组中的所有元素执行一个由您提供的reducer函数(升序和降序执行),将其减少为单一输出值。

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((acc, val) => acc + val, 0); // 15

k. some() 和 every(): 测试数组中的某些元素是否满足某条件。some()是只要有一个满足就返回trueevery()必须所有都满足才返回true

const numbers = [1, 2, 3, 4, 5];

const someGreaterThan2 = numbers.some(num => num > 2); // true

const everyGreaterThan0 = numbers.every(num => num > 0);

10.模块化(export、import)

11. 新增数据结构:set、map

12. generator

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com