返回

多种方法掌握JS数组遍历及兼容性处理 (polyfill)

前端

重新认识JavaScript系列文章连载中。数组遍历作为最基础的数组操作,在日常开发中大量使用。

掌握了数组遍历的这七种方法,就能从多个维度来操作数组,并能应对不同兼容性问题。

两种基本语法

在探索遍历方法之前,先来看下两种基本的遍历语法。

// 普通for循环
for(let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

// for...of
for (const item of arr) {
  console.log(item);
}

for...of主要用于遍历类数组对象,但也可以用于遍历数组,其本质就是遍历对象的所有可枚举属性。

Array.prototype.forEach()

forEach()是用来遍历数组的,但它的返回值并不是一个新数组,而是undefined。

const arr = [1, 2, 3];
arr.forEach((item) => {
  console.log(item);
});

// 输出
// 1
// 2
// 3

forEach()可以接受三个参数,分别是当前元素、当前元素索引、当前数组。第一个和第三个参数是必须的,第二个可选。

Array.prototype.map()

map()和forEach()很相似,但map()会返回一个新数组,新数组的长度和原数组相同。

const arr = [1, 2, 3];
const newArr = arr.map((item) => {
  return item * 2;
});

// newArr => [2, 4, 6]

Array.prototype.filter()

filter()和forEach()、map()的区别是,它只会返回那些满足条件的元素。

const arr = [1, 2, 3, 4, 5, 6];
const newArr = arr.filter((item) => {
  return item > 3;
});

// newArr => [4, 5, 6]

Array.prototype.some()

some()和filter()很相似,但some()只要有一个元素满足条件就会返回true,否则返回false。

const arr = [1, 2, 3, 4, 5, 6];
const result = arr.some((item) => {
  return item > 3;
});

// result => true

Array.prototype.every()

every()和some()相反,只有所有元素都满足条件才会返回true。

const arr = [1, 2, 3, 4, 5, 6];
const result = arr.every((item) => {
  return item > 3;
});

// result => false

Array.prototype.reduce()

reduce()可以将数组中的所有元素累积成一个值。

const arr = [1, 2, 3, 4, 5, 6];
const result = arr.reduce((pre, cur) => {
  return pre + cur;
});

// result => 21

Array.prototype.findIndex()

findIndex()可以找到数组中第一个满足条件的元素的索引。

const arr = [1, 2, 3, 4, 5, 6];
const index = arr.findIndex((item) => {
  return item > 3;
});

// index => 3

兼容性问题

forEach()、map()、filter()、some()、every()、reduce()、findIndex()这七种方法都是ES5中新增的方法,所以IE8及以下的浏览器都不支持。

为了解决兼容性问题,可以使用polyfill来模拟实现这些方法。

polyfill的实现原理很简单,就是用其他方法来模拟实现这些方法。

例如,可以使用forEach()来模拟实现map():

Array.prototype.map = function (callback) {
  const arr = this;
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    newArr.push(callback(arr[i]));
  }
  return newArr;
};

结语

上面介绍了JavaScript数组遍历的七种方法及其兼容性处理。掌握这些方法,能够大大提高开发效率,并能更好地解决兼容性问题。

在实际开发中,应根据具体情况选择合适的方法来遍历数组。