数组遍历 | 前端面试

133 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第3天

大家好,我是朝朝,我有一只猫,叫乐乐,但是它从来不晓得自己叫这个名字orz

面试的时候很常见的数组遍历,实际开发的时候也确实用数组的形式保存对象的形式比单纯保存成对象更加具有延展性

那么,有一个变量,叫做arr,我们要来遍历它了

let arr = [1,2,3,4,5,6];
for

老生常谈了,中规中矩

for (let index = 0; index < arr.length; index++) {
    console.log(index);
}
forEach

数组自带api,没有返回值,纯粹遍历数组

let res = arr.forEach((value, index) => {
    console.log(value, index);
})
console.log(res); // undefined

for in

以任意顺序迭代一个除了Symbal以外的可枚举的属性,包括继承的可枚举属性,方便调试检查对象的属性

获取key值

let triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
  this.color = 'red';
}

ColoredTriangle.prototype = triangle;

let obj = new ColoredTriangle();

for (let key in obj) {
    console.log(obj[key]);
} // red a b c

for of

for...of语句在可地带对象(Array、Map、Set、String、TypeArray、arguments)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句

获取value值

(function() {
  for (let argument of arguments) {
    console.log(argument);
    // 可以使用break, throw或return终止迭代
  }
})(1, 2, 3);

不能遍历对象

image.png

map

原数组的每一个值都调用提供的函数,并且返回一个新的值,组成一个新的数组

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// [2, 8, 18, 32]

const map2 = array1.map(x => {});
console.log(map2); 
// [undefined, undefined, undefined, undefined]

every

数组的每一项都符合提供函数的条件,则返回true,否则就是false

[12, 5, 8, 130, 44].every(x => x >= 10); // false

some

数组只要有意向符合提供函数的条件,则返回true,否则就是false

[12, 5, 8, 130, 44].some(item => item >120) // true

reduce

累计计算

语法
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)
// 每一次循环
// previousValue 前面一次迭代返回的值
// currentValue 此次迭代的值
// currentIndex currentValue的索引
// array 原始数组
// 第一次迭代没有previousValue值,使用initialValue表示初始值

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  0
);
console.log(sumWithInitial);

filter

数组过滤出符合条件的元素,返回新的数组

console.log([1,2,3,4].filter(item => item > 2));
// [3, 4]

浅浅介绍