JS中的12种遍历方法

77 阅读4分钟

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

得不得奖的无所谓希望能强迫自己闯一关╮( ̄▽ ̄)╭

前言

记录JS中的12种循环遍历方法
有误请多多指正,附上女神图保命 [手动狗头]
学习已完成

  • 1.for
  • 2.for in
  • 3.for of
  • 4.Array.prototype.forEach()
  • 5.Array.prototype.map()
  • 6.Array.prototype.filter()
  • 7.Array.prototype.some()
  • 8.Array.prototype.every()
  • 9.Array.prototype.reduce()
  • 10.Array.prototype.reduceRight()
  • 11.while
  • 12.do while

1.for

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for (let i = 0; i < array.length; i++) {
    console.log(i); // 0 1 2 3 4 5 6 7 8 9
}

2.for in

主要用于遍历普通对象,不仅遍历自身的属性,还会去遍历原型链上的属性

let obj = { name: 'xiaoming', age: 18, height: 180 }
Object.prototype.weight = 70 // 给原形链上赋上wieght
for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) { // 保持不遍历原型链上的属性
        console.log('obj[key]: ', obj[key]); //  xiaoming 18 180
    } else {
        console.log('obj[weight]: ', obj[key]); // obj[weight]:  70
    }
}

3.for of

ES6 中新增的语句,用来替代 for in 和 forEach,允许遍历 Array(数组), String(字符串), Map(映射), Set(集合)等可迭代(Iterable data)的数据结构,但它有兼容性问题。
是直接用来遍历值得 iterator 就是对应的值

const array = [5, 1, 2, 3, 4]
for (const iterator of array) {
    console.log('iterator: ',iterator); // 5 1 2 3 4
}
const str = 'string'
for (const iterator of str) {
    console.log('iterator: ',iterator); // s t r i n g
}
const setA = new Set([1, "some text", { a: 1 }])
for (const iterator of setA) {
    console.log('iterator: ', iterator); // 1, some text, { a: 1 }
}

4.Array.prototype.forEach()

forEach()  方法对数组的每个元素执行一次给定的函数。

const array = [5, 1, 2, 3, 4]
array.forEach((element, i, arr) => {
    console.log('element: ', element, i, arr); // element 当前遍历值,索引,数组
}, this); // this 是传给 forEach里的 callback 函数的用于获取外部this的

5.Array.prototype.map()

map()  方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

const array = [1, 4, 9, 16];
const mapA = array.map((element, i, arr) => { // element,i,arr 分别表示当前遍历值,索引,数组
    return element * 2
}, this); // this 是传给 forEach里的 callback 函数的用于获取外部this的 */
console.log(mapA); // [2, 8, 18, 32]

6.Array.prototype.filter()

filter()  方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

const array = [1, 4, 9, 16];
const filterA = array.filter((element, i, arr) => { // element,i,arr 分别表示当前遍历值,索引,数组
    return element > 4
}, this); // this 是传给 forEach里的 callback 函数的用于获取外部this的 */
console.log(filterA); // [9, 16]

7.Array.prototype.some()

some()  方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。 数组中有至少一个元素通过回调函数的测试就会返回 true所有元素都没有通过回调函数的测试返回值才会为 false

备注: :若收到一个空数组,此方法在一切情况下都会返回 false

const array = [1, 2, 3, 4, 5];
const someA = array.some((element, i, arr) => { // element,i,arr 分别表示当前遍历值,索引,数组
   return element % 2 === 0
}, this); // this 是传给 forEach里的 callback 函数的用于获取外部this的
console.log(someA) // true

8.Array.prototype.every()

some() 反过来,every()  方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。 如果回调函数的每一次返回都为 truthy 值,返回 true ,否则只要有一次是 false 就返回 false

备注: :若收到一个空数组,此方法在一切情况下都会返回 true

const array = [1, 30, 39, 29, 10, 13];
const everyA = array.every((element, i, arr) => { // element,i,arr 分别表示当前遍历值,索引,数组
    return element < 20;
 }, this); // this 是传给 forEach里的 callback 函数的用于获取外部this的
console.log(everyA); // false

9.Array.prototype.reduce()

reduce()  方法对数组中的每个元素按序执行一个开发者提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
reducer 逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果是当前元素之前所有元素的总和)——直到没有更多的元素被相加。 其实就是 reduce() 方法接收一个函数作为累加器,数组中的每个值(从头到尾)开始缩减,最终计算为一个值。

const array = [1, 2, 3, 4, 5]; // 此时callback会被调用 4次 累加起来
// previousValue,currentValue,i,arr 分别表示上一次调用 callbackFn 时的返回值,当前数组中正在处理的元素,索引,数组
const reduceA = array.reduce((previousValue, currentValue, i, arr) => { 
    return previousValue + currentValue;
});
console.log(reduceA); // 15

设置初始值

const initialValue = 6;
// 设置初始值,会先替换 previousValue,之后再继续累加
const reduceB = array.reduce((previousValue, currentValue, i, arr) => previousValue + currentValue, initialValue);
console.log(reduceB); // 21

将二维数组转化为一维

let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
    ( previousValue, currentValue ) => previousValue.concat(currentValue),
    []
)
// flattened is [0, 1, 2, 3, 4, 5]

计算数组中每个元素出现的次数

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']
let countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

按属性对 object 分类

let people = [
    { name: 'Alice', age: 21 },
    { name: 'Max', age: 20 },
    { name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
    return objectArray.reduce(function (acc, obj) {
        let key = obj[property]
        if (!acc[key]) {
            acc[key] = []
        }
        acc[key].push(obj)
        return acc
    }, {})
}
let groupedPeople = groupBy(people, 'age')
console.log('groupedPeople: ', groupedPeople);
// groupedPeople is:
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }
// countedNames is: { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

10.Array.prototype.reduceRight()

Array.prototype.reduce相反反向开始遍历

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);
console.log(array1); // Array [4, 5, 2, 3, 0, 1]

11.while

while 语句可以在某个条件表达式为真的前提下,循环执行指定的一段代码,直到那个表达式不为真时结束循环。

let n = 0;
while (n < 3) {
  n++;
}
console.log(n); // 3

12.do while

do...while 语句创建一个执行指定语句的循环,直到condition值为 false。在执行statement 后检测condition,所以指定的statement至少执行一次。

语法
do
   statement
while (condition);
var result = '',
    i = 0;
do {
    i += 1;
    result += i + ' ';
} while (i < 5);
console.log('result: ', result);

最后

以上的方式总结只是自己学习总结或查阅文档记录,有其他方式欢迎各位大佬评论
渣渣一个,欢迎各路大神多多指正,不求赞,只求监督指正( ̄. ̄)
有关文章经常被面试问到可以帮忙留下言,小弟也能补充完善完善一起交流学习,感谢各位大佬(~ ̄▽ ̄)~