ES6 引入了许多新的数组和对象操作方法,使得 JavaScript 编程更加方便和高效。下面分别介绍一些常用的数组和对象操作方法:
一、数组操作方法
1、Array.from()
- 将类数组对象或可迭代对象转换为真正的数组。
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const newArray = Array.from(arrayLike); // ['a', 'b']
2、Array.prototype.find()
- 返回数组中满足提供的测试函数的第一个元素的值。
const numbers = [10, 20, 30, 40];
const found = numbers.find(num => num > 25); // 30
3、 Array.prototype.findIndex()
- 返回数组中满足提供的测试函数的第一个元素的索引。
const numbers = [10, 20, 30, 40];
const foundIndex = numbers.findIndex(num => num > 25); // 2
4、Array.prototype.filter()
- 创建一个新数组,其中包含所有通过测试的元素。
const numbers = [10, 20, 30, 40];
const filtered = numbers.filter(num => num > 25); // [30, 40]
5、Array.prototype.map()
- 创建一个新数组,其结果是该数组中每个元素调用一个提供的函数后的返回值。
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]
6、Array.prototype.reduce()
- 对数组中的每个元素执行一个提供的函数,并将其结果汇总为单个值。
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, current) => acc + current, 0); // 10
7、Array.prototype.includes()
- 判断数组是否包含某个特定元素。
const numbers = [1, 2, 3];
const includesTwo = numbers.includes(2); // true
二、对象操作方法
1、Object.keys()
- 返回一个由对象的自身可枚举属性组成的数组。
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj); // ['a', 'b', 'c']
2、Object.values()
- 返回一个包含对象自身的所有可枚举值的数组。
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj); // [1, 2, 3]
3、Object.entries()
- 返回一个给定对象自身可枚举属性的键值对数组。
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3]]
4、Object.assign()
- 用于将所有可枚举属性的值从一个或多个源对象复制到目标对象,并返回目标对象。
const target = { a: 1 };
const source = { b: 2, c: 3 };
const merged = Object.assign(target, source); // { a: 1, b: 2, c: 3 }
这些方法不仅提升了 JavaScript 编程的效率,还使代码更加清晰和易于维护。在实际开发中,结合这些方法能够更好地处理数组和对象的操作需求。