ES6-learning:数组功能改进的实战应用
【免费下载链接】ES6-learning《深入理解ES6》教程学习笔记项目地址: https://gitcode.com/gh_mirrors/es6l/ES6-learning
ES6-learning是《深入理解ES6》的教程学习笔记项目,专注于讲解ES6带来的各种新特性。本文将聚焦于ES6中数组功能的改进,帮助开发者快速掌握这些实用的新特性,提升JavaScript编程效率。
一、创建数组的新方式
1.1 Array.of():消除歧义的数组创建
ES5中使用new Array()创建数组时存在行为不一致的问题:当传入数字参数时创建指定长度的空数组,传入其他类型参数时则创建包含该元素的数组。ES6的Array.of()方法彻底解决了这一歧义。
// ES5行为 const a = new Array(2); // [undefined, undefined](长度为2的空数组) const b = new Array("2"); // ["2"](包含一个元素的数组) // ES6改进 const c = Array.of(2); // [2](包含数字2的数组) const d = Array.of("2"); // ["2"](包含字符串"2"的数组)1.2 Array.from():类数组转数组的利器
Array.from()方法能将类数组对象(如arguments)和可迭代对象(如Set、Map)转换为真正的数组,还支持映射转换和去重等实用功能。
基础转换示例:
function test(a, b) { const arr = Array.from(arguments); // 将arguments转为数组 console.log(arr); // [1, 2] } test(1, 2);映射转换示例:
function test(a, b) { // 第二个参数作为映射函数 const arr = Array.from(arguments, value => value + 2); console.log(arr); // [3, 4] } test(1, 2);数组去重应用:
function uniqueArray() { return Array.from(new Set(...arguments)); // 利用Set去重特性 } const s = uniqueArray([1, "2", 3, 3, "2"]); console.log(s); // [1, "2", 3]二、数组实例的新增方法
2.1 元素查找:find()与findIndex()
- find():返回数组中第一个符合条件的元素
- findIndex():返回数组中第一个符合条件的元素索引
const arr = [1, "2", 3, 3, "2"]; // 查找第一个数字类型元素 console.log(arr.find(n => typeof n === "number")); // 1 // 查找第一个数字类型元素的索引 console.log(arr.findIndex(n => typeof n === "number")); // 02.2 数组填充:fill()
fill()方法用指定值替换数组元素,支持指定替换范围(开始索引和结束索引)。
const arr = [1, 2, 3]; // 全部替换 console.log(arr.fill(4)); // [4, 4, 4] // 从索引1开始替换 const arr1 = [1, 2, 3]; console.log(arr1.fill(4, 1)); // [1, 4, 4] // 从索引0到2(不包含2)替换 const arr2 = [1, 2, 3]; console.log(arr2.fill(4, 0, 2)); // [4, 4, 3]2.3 数组复制:copyWithin()
copyWithin()方法将数组内部指定范围的元素复制到目标位置,覆盖原有元素。
const arr = [1, 2, 3, 4, 5]; // 从索引3开始复制(默认从0开始复制) console.log(arr.copyWithin(3)); // [1, 2, 3, 1, 2] // 从索引3开始复制,从索引1开始取值 const arr1 = [1, 2, 3, 4, 5]; console.log(arr1.copyWithin(3, 1)); // [1, 2, 3, 2, 3] // 从索引3开始复制,从索引1到2(不包含2)取值 const arr2 = [1, 2, 3, 4, 5]; console.log(arr2.copyWithin(3, 1, 2)); // [1, 2, 3, 2, 5]三、学习资源与总结
ES6数组功能的改进虽然内容不多,但实用性极强。掌握Array.of()、Array.from()创建数组的新方式,以及find()、findIndex()、fill()、copyWithin()等新增方法,能显著提升数组操作效率。
完整的学习笔记可参考项目文档:doc/10、《深入理解ES6》笔记—— 改进数组的功能.md
通过这些改进,ES6让数组操作更加直观、灵活,是每个JavaScript开发者必备的技能。赶紧动手实践,体验这些新特性带来的便利吧! 🚀
【免费下载链接】ES6-learning《深入理解ES6》教程学习笔记项目地址: https://gitcode.com/gh_mirrors/es6l/ES6-learning
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考