ES6中数组的高级用法

1. 箭头函数和数组方法的结合:

使用箭头函数结合数组方法可以简化代码:

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

// 使用箭头函数的 map 方法
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // 输出:[2, 4, 6, 8, 10]

2. 解构赋值和数组方法的结合:

const point = [10, 20];

// 使用解构赋值和箭头函数的 map 方法
const movedPoint = point.map(([x, y]) => ({ x: x + 10, y: y + 10 }));
console.log(movedPoint); // 输出:[{ x: 20, y: 30 }]

3. 扩展运算符:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// 合并数组
const combined = [...arr1, ...arr2];
console.log(combined); // 输出:[1, 2, 3, 4, 5, 6]

// 克隆数组
const clone = [...arr1];
console.log(clone); // 输出:[1, 2, 3]

4. 使用 find、filter、some 和 every 方法:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

// 查找符合条件的对象
const user = users.find(user => user.id === 2);
console.log(user); // 输出:{ id: 2, name: 'Bob' }

// 过滤数组
const filteredUsers = users.filter(user => user.name.startsWith('A'));
console.log(filteredUsers); // 输出:[{ id: 1, name: 'Alice' }]

// 检查是否有符合条件的对象
const hasBob = users.some(user => user.name === 'Bob');
console.log(hasBob); // 输出:true

// 检查是否所有对象都满足条件
const allNamesContainC = users.every(user => user.name.includes('c'));
console.log(allNamesContainC); // 输出:false

5. 使用 reduce 方法:

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

// 求和
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 输出:15

// 扁平化数组
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArray.reduce((acc, cur) => [...acc, ...cur], []);
console.log(flattenedArray); // 输出:[1, 2, 3, 4, 5, 6]

6. 使用 map 方法进行对象转换:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

// 将数组中的对象转换为另一种形式
const userNames = users.map(user => user.name);
console.log(userNames); // 输出:['Alice', 'Bob', 'Charlie']

7. 使用 includes 方法检查元素是否存在:

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

// 检查数组是否包含某个元素
const hasThree = numbers.includes(3);
console.log(hasThree); // 输出:true

8. 使用 flat 方法扁平化多维数组:

const nestedArray = [[1, 2], [3, [4, 5]], 6];

// 扁平化多维数组
const flatArray = nestedArray.flat();
console.log(flatArray); // 输出:[1, 2, 3, [4, 5], 6]

// 可以指定扁平化的层级
const flatArray2 = nestedArray.flat(2);
console.log(flatArray2); // 输出:[1, 2, 3, 4, 5, 6]

9. 使用 from 方法将类数组对象或可迭代对象转换为数组:

const string = 'hello';

// 将字符串转换为字符数组
const charArray = Array.from(string);
console.log(charArray); // 输出:['h', 'e', 'l', 'l', 'o']

// 将 Set 转换为数组
const set = new Set([1, 2, 3]);
const arrayFromSet = Array.from(set);
console.log(arrayFromSet); // 输出:[1, 2, 3]

10. 使用 Array.prototype 方法进行函数式编程:

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

// 使用 map、filter 和 reduce 实现链式操作
const result = numbers
  .map(num => num * 2)
  .filter(num => num > 5)
  .reduce((acc, cur) => acc + cur, 0);
console.log(result); // 输出:24

 

posted on 2024-04-17 16:17  萬事順意  阅读(18)  评论(0编辑  收藏  举报