返回

JS数组知识点整理(ES6+新增)

前端





## **JS数组知识点整理** 

### **构造函数** 

**Array**  是 JavaScript 的原生对象,同时也是一个构造函数,可以用它生成新的数组。创建数组,直接使用数组字面量是更好的做法。

```javascript
const arr = new Array(); // 创建一个空数组
const arr2 = new Array(5); // 创建一个长度为 5 的数组,元素都为 undefined
const arr3 = new Array(1, 2, 3); // 创建一个包含三个元素的数组

静态方法

Array.isArray()

Array.isArray() 返回一个布尔值,表示参数是否是数组。

Array.isArray([]); // true
Array.isArray({}); // false

Array.from()

Array.from() 将可迭代对象转换为数组。

Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
Array.from(document.querySelectorAll('p')); // [p, p, p]

Array.of()

Array.of() 创建一个包含任意数量元素的新数组。

Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]

实例方法

Array.prototype.copyWithin()

Array.prototype.copyWithin() 将数组的一部分复制到数组的另一部分。

const arr = [1, 2, 3, 4, 5];
arr.copyWithin(2, 0); // [1, 1, 2, 3, 5]

Array.prototype.fill()

Array.prototype.fill() 用给定的值填充数组。

const arr = [1, 2, 3, 4, 5];
arr.fill(0); // [0, 0, 0, 0, 0]

Array.prototype.find()

Array.prototype.find() 返回数组中第一个满足给定条件的元素。

const arr = [1, 2, 3, 4, 5];
const firstEven = arr.find(element => element % 2 === 0); // 2

Array.prototype.findIndex()

Array.prototype.findIndex() 返回数组中第一个满足给定条件的元素的索引。

const arr = [1, 2, 3, 4, 5];
const firstEvenIndex = arr.findIndex(element => element % 2 === 0); // 1

Array.prototype.includes()

Array.prototype.includes() 返回一个布尔值,表示数组是否包含给定的值。

const arr = [1, 2, 3, 4, 5];
arr.includes(3); // true
arr.includes(6); // false

Array.prototype.keys()

Array.prototype.keys() 返回一个迭代器,可以遍历数组的键。

const arr = [1, 2, 3, 4, 5];
for (const key of arr.keys()) {
  console.log(key); // 0, 1, 2, 3, 4
}

Array.prototype.values()

Array.prototype.values() 返回一个迭代器,可以遍历数组的值。

const arr = [1, 2, 3, 4, 5];
for (const value of arr.values()) {
  console.log(value); // 1, 2, 3, 4, 5
}

Array.prototype.entries()

Array.prototype.entries() 返回一个迭代器,可以遍历数组的键值对。

const arr = [1, 2, 3, 4, 5];
for (const [key, value] of arr.entries()) {
  console.log(key, value); // 0 1, 1 2, 2 3, 3 4, 4 5
}

总结

本篇文章对JS数组知识点进行了整理,涵盖了ES6+新增的内容。希望对读者有所帮助。