JS 数组之-遍历

294 阅读2分钟

*一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第23天,点击查看活动详情

要说到项目开发中用到最多的数据类型那就非Array数组莫属了,尤其是大型项目对数组的使用的好坏也会对页面的性能有一定的影响。开发中我们平常用那些方式遍历数组呢,在数组中查找你想要的数据呢,都用过那些Array提供的方法呢,这里列举了一下常用的Array相关的方法。

遍历

下面列举我们都常用的变量方法 for循环:我们学习编程第一个学到的数组遍历方法

const data = [1, 2, 3, 4];
for (let index = 0; index < data.length; index++) {
  const element = data[index];
  console.log(element)
}

forEach: 最常用的遍历方法之一,可以不用定义index等索引遍历,直接使用,它是Array提供的一个方法,接收一个函数用于获取每一项值,该方法不能终止数组的遍历,方法没有返回值。

const data = [1, 2, 3, 4];
data.forEach((element, index) => {
  console.log(element, index); // element 为数组中的每一项, index为数组中的索引
});

map: 最最常用的遍历方法之一,和forEach相似都是Array提供的一个方法,都接收一个函数用于获取每一项值,也不能终止。但是和forEach的区别是它有返回值,返回一个新的数组。

const data = [1, 2, 3, 4];
const data1 = data.map((element, index) => { // 返回一个都是1的数组。
  console.log(element, index); // element 为数组中的每一项, index为数组中的索引
  return 1; // 并不能终止循环。
});
console.log(data1); // 1,1,1,1

for in: 循环遍历一个对象的可枚举属性,包括这个对象继承自原型链上的可枚举属性,数组也是对象也是可枚举的它的枚举属性是索引值,因此我们常用于变量数组和对象的属性,当然字符串也可以遍历。可以终止循环。

const data = [1, 2, 3, 4];
const obj = { name: 'xiaming', age: 12 };
for (const key in obj) {
  if (Object.hasOwnProperty.call(obj, key)) {
    const element = obj[key]; // key = name, age
    console.log(key, element);
  }
}
for (const key in data) {
  if (Object.hasOwnProperty.call(data, key)) {
    const element = data[key]; // key = 0, 1, 2, 3
    console.log(key, element);
  }
}

for of: ES6新增的循环方法, 可以遍历数组、Set 和 Map 结构等数据结构,只要数据结构包含了Symbol.iterator属性,就被视为具有 iterator 接口,就可以用for...of循环遍历它的成员。可以终止循环。

const data = [1, 2, 3, 4];
const dataSet = new Set(data);
for (const iterator of data) {
  console.log(iterator); // 1, 2, 3, 4
}
for (const iterator of dataSet ) {
  console.log(iterator); // 1, 2, 3, 4
}

总结

这些遍历的方法我们应该使用那个,它们有什么区别,其实for循环时性能最好的一个遍历方式,但是性能差其实微乎其微。当我们要中途终止数组这个场景时可以使用for循环、for of,如果还要所引位置那就用for循环,for of很少用于数组遍历,一般是数组,如果我们不用终止遍历就能采用map、forEach就用他们,毕竟写起来方便,也可以获取到索引值。如果要对数组改造数据修改就用map循环。