24个JavaScript循环遍历方法(一数组方法)

  24个JavaScript循环遍历方法

  24个JavaScript循环遍历方法

  一 数组方法 1. forEach()

  forEach 方法用于调用数组的每一个元素,并将元素传递给回调函数。数组中的每一个值都会调用回调函数。

   array.forEach(function(currentValue,index,arr),thisValue)

  该方法的第一个参数为回调函数,是必传的,它有三个参数:

   let arr = [1,2,3,4,5]

  1. arr.forEach((item, index, arr) => {
  2. console.log(index+":"+item)
  3. })

  该方法还可以有第二个参数,用来绑定回调函数内部this变量(前提是回调函数不是箭头函数,因为箭头函数没有this)

   let arr = [1,2,3,4,5]

  1. let arr1 = [9,8,7,6,5]
  2. arr.forEach(function(item, index, arr){
  3. console.log(this[index]) // 9 8 7 6 5
  4. }, arr1)

  注意:

  2. map()

  map() 方法会返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值 。该方法按照原始数组元素顺序依次处理元素。

   array.map(funciton(currentValue,index,arr),thisValue)

  该方法的第一个参数为回调函数,是必传的,它有三个参数:

   let arr = [1, 2, 3];

  1. arr.map(item => {
  2. return item + 1;
  3. })
  4. // 输出结果: [2, 3, 4]

  该方法的第二个参数用来绑定参数函数内部的this变量,是可选的:

   let arr = ['a', 'b', 'c'];

  1. let newArr=[1, 2].map(function (item) {
  2. return this[item];
  3. }, arr)
  4. console.log(newArr)
  5. // 输出结果: ['b', 'c']

  该方法还可以进行链式调用:

   let arr = [1, 2, 3];

  1. arr.map(item => item + 1).map(item => item + 1)
  2. // 输出结果: [3, 4, 5]

  注意:

  3. for of

  for...of 语句创建一个循环来迭代可迭代的对象,在ES6中引入的for…of 循环,以替代for…in 和forEach(),并支持新的迭代协议

   for (variable of iterable) {

  1. statement
  2. }

  该方法有两个参数:

   let arr = [

  1. {id:1, value:'hello'},
  2. {id:2, value:'world'},
  3. {id:3, value:'JavaScript'}
  4. ]
  5. for (let item of arr) {
  6. console.log(item);
  7. }
  8. // 输出结果:{id:1, value:'hello'} {id:2, value:'world'} {id:3, value:'JavaScript'}

  注意

  4. filter()

  filter() 方法用于过滤数组,满足条件的元素会被返回,它的参数是一个回调函数,所有素组元素依次执行该函数,返回结果为true的元素会被返回,如果没有符合条件的元素,则返回空数组

   array.filter(function(currentValue,index,arr), thisValue)

  该方法的第一个参数为回调函数,是必传的,它有三个参数:

   const arr = [1, 2, 3, 4, 5]

  1. arr.filter(item => item > 2)
  2. // 输出结果:[3, 4, 5]

  同样,它也有第二个参数,用来绑定参数函数内部的this变量。

  可以使用filter()方法来移除数组中的undefined、null、NAN等值:

   let arr = [1, undefined, 2, null, 3, false, '', 4, 0]

  1. arr.filter(Boolean)
  2. // 输出结果:[1, 2, 3, 4]

  注意

  5. some()、every()

  some() 方法会对数组中的每一项进行遍历,只要有一个元素符合条件,就会返回true,且剩余的元素不会再进行检测,否则就会返回false

  every() 方法会对数组中的每一项进行遍历,只有所有的元素都符合条件,才返回true,如果数组中检测到一个元素不满足,则整个表达式返回false,且剩余的元素不会再进行检测

   array.some(function(currentValue,index,arr),thisValue)

  1. array.every(function(currentValue,index,arr),thisValue)

  两个方法的第一个参数为回调函数,是必传的,它有三个参数:

   let arr = [1, 2, 3, 4, 5]

  1. arr.some(item => item > 4)
  2. // 输出结果:true
  3. let arr = [1, 2, 3, 4, 5]
  4. arr.every(item => item > 0)
  5. // 输出结果:true

  注意

  6. reduce()、reduceRight()

  reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 可以作为一个高阶函数,用于函数的 compose

   array.reduce(function(total,currentValue,currentIndex,arr),initialValue)

  reduce 方法会为数组中的每一个元素依次执行回调函数,不包括数组中被删除或者从未被赋值的元素,回调函数接受四个参数

  该方法的第二个参数是initialValue,表示传递给函数的初始值(作为第一次调用callback的第一个参数)

   let arr = [1, 2, 3, 4]

  1. let sum = arr.reduce(function (pre, cur, index, arr) {
  2. console.log(pre, cur, index);
  3. return pre + cur
  4. })
  5. console.log(arr, sum);
  6. // 输出结果:1 2 1
  7. // 3 3 2
  8. // 6 4 3
  9. // [1, 2, 3, 4] 10

  再来加一个初始值试试:

   let arr = [1, 2, 3, 4]

  1. let sum = arr.reduce((prev, cur, index, arr) => {
  2. console.log(prev, cur, index);
  3. return prev + cur;
  4. }, 5)
  5. console.log(arr, sum);
  6. // 输出结果: 5 1 0
  7. // 6 2 1
  8. // 8 3 2
  9. // 11 4 3
  10. // [1, 2, 3, 4] 15

  由此可以得出结论:如果没有提供初始值initialValue,reduce会从索引1的地方开始执行callback方法,跳过第一个索引。如果提供了初始值initialValue,从索引0开始执行

  reduceRight() 方法和的reduce()用法几乎一致,只是该方法是对数组进行倒序遍历的,而reduce()方法是正序遍历的。

   let arr = [1, 2, 3, 4]

  1. let sum = arr.reduceRight((prev, cur, index, arr) => {
  2. console.log(prev, cur, index);
  3. return prev + cur;
  4. }, 5)
  5. console.log(arr, sum);
  6. //输出结果
  7. //5 4 3
  8. //9 3 2
  9. //12 2 1
  10. //14 1 0
  11. //[1, 2, 3, 4] 15

  注意

  7. find() 、findIndex()

  js遍历数组的方法_js 遍历 对象数组_js 对象数组遍历

  find() 方法返回通过函数内判断的数组的第一个元素的值。当数组中的元素在测试条件时返回true时,find()返回符合条件的元素,之后的值不会再调用执行函数。如果没有符合条件的元素返回undefined

  findIndex() 方法返回传入一个测试函数符合条件的数组第一个元素位置(索引)。当数组中的元素在函数条件时返回true时,findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。如果没有符合条件的元素返回-1

   array.find(function(currentValue, index, arr),thisValue)

  1. array.findIndex(function(currentValue, index, arr), thisValue)

  两个方法的第一个参数为回调函数,是必传的,它有三个参数:

   let arr = [1, 2, 3, 4, 5]

  1. arr.find(item => item > 2)
  2. // 输出结果:3
  3. let arr = [1, 2, 3, 4, 5]
  4. arr.findIndex(item => item > 2)
  5. // 输出结果:2

  find()和 find Index() 两个方法几乎一样,只是返回结果不一样

  注意

  8. keys()、 values() 、 entries()

  三个方法都返回一个数组的迭代对象,对象的内容不太相同:

   array.keys()

  1. array.values()
  2. array.entries()

  这三个方法都没有参数

   let arr = ["Banana", "Orange", "Apple", "Mango"];

  1. const iterator1 = arr.keys();
  2. const iterator2 = arr.values()
  3. const iterator3 = arr.entries()
  4. for (let item of iterator1) {
  5. console.log(item);
  6. }
  7. // 输出结果: 0 1 2 3
  8. for (let item of iterator2) {
  9. console.log(item);
  10. }
  11. // 输出结果:Banana Orange Apple Mango
  12. for (let item of iterator3) {
  13. console.log(item);
  14. }
  15. // 输出结果:[0, 'Banana'] [1, 'Orange'] [2, 'Apple'] [3, 'Mango']

  总结 方法是否改变原数组是否有返回值特点

  forEach()

  否

  没有返回值

  map()

  否

  有

  可链式调用

  for of

  否

  无

  for…of遍历具有Iterator迭代器的对象的属性js遍历数组的方法,返回的是数组的元素、对象的属性值,不能遍历普通的obj对象,将异步循环变成同步循环

  filter()

  否

  有

  过滤数组,返回包含符合条件的元素的数组,可链式调用

  js 遍历 对象数组_js 对象数组遍历_js遍历数组的方法

  every()、some()

  否

  有

  some()只要有一个是true,便返回true;而every()只要有一个是false,便返回false.

  find()、findIndex()

  否

  有

  find()返回的是第一个符合条件的值;findIndex()返回的是第一个返回条件的值的索引值

  reduce()、reduceRight()

  否

  有

  reduce()对数组正序操作;reduceRight()对数组逆序操作

  keys()、values()、entries()

  否

  无

  keys() 返回数组的索引值;values() 返回数组元素;entries() 返回数组的键值对。

  二 对象遍历方法 1. for in

  for…in 主要用于循环对象属性。循环中的代码每执行一次,就会对对象的属性进行一次操作。

   for (var ** in object) {

  1. 执行的代码块
  2. }

  其中两个参数:

   var obj = {a: 1, b: 2, c: 3};

  1. for (var i in obj) {
  2. console.log('键名:', i);
  3. console.log('键值:', obj[i]);
  4. }
  5. //输出结果
  6. //键名:a
  7. //键值: 1
  8. //键名:b
  9. //键值: 2
  10. //键名:c
  11. //键值: 3

  注意

  2. Object.keys()、Object.values()、Object.entries()

  这三个方法都用来遍历对象,它会返回一个由给定对象的自身可枚举属性(不含继承的和Symbol属性)组成的数组,数组元素的排列顺序和正常循环遍历该对象时返回的顺序一致,这个三个元素返回的值分别如下:

   let obj = {

  1. id: 1,
  2. name: 'hello',
  3. age: 18
  4. };
  5. console.log(Object.keys(obj)); // 输出结果: ['id', 'name', 'age']
  6. console.log(Object.values(obj)); // 输出结果: [1, 'hello', 18]
  7. console.log(Object.entries(obj)); // 输出结果: [['id', 1], ['name', 'hello'], ['age', 18]

  注意

  3. Object.getOwnPropertyNames()

  Object.getOwnPropertyNames()方法与Object.keys()类似,也是接受一个对象作为参数,返回一个数组,包含了该对象自身的所有属性名。但它能返回不可枚举的属性。

   let a = ['Hello', 'World'];

  1. Object.keys(a) // ["0", "1"]
  2. Object.getOwnPropertyNames(a) // ["0", "1", "length"]

  这两个方法都可以用来计算对象中属性的个数

   var obj = { 0: "a", 1: "b", 2: "c"};

  1. Object.getOwnPropertyNames(obj) // ["0", "1", "2"]
  2. Object.keys(obj).length // 3
  3. Object.getOwnPropertyNames(obj).length // 3

  4. Object.getOwnPropertySymbols()

  Object.getOwnPropertySymbols() 方法返回对象自身的 Symbol 属性组成的数组,不包括字符串属性:

   let obj = {a: 1}

  1. // 给对象添加一个不可枚举的 Symbol 属性
  2. Object.defineProperties(obj, {
  3. [Symbol('baz')]: {
  4. value: 'Symbol baz',
  5. enumerable: false
  6. }
  7. })
  8. // 给对象添加一个可枚举的 Symbol 属性
  9. obj[Symbol('foo')] = 'Symbol foo'
  10. Object.getOwnPropertySymbols(obj).forEach((key) => {
  11. console.log(obj[key])
  12. })
  13. // 输出结果:Symbol baz Symbol foo

  5. Reflect.ownKeys()

  Reflect.ownKeys() 返回一个数组,包含对象自身的所有属性。它和Object.keys()类似js遍历数组的方法,Object.keys()返回属性key,但不包括不可枚举的属性,而Reflect.ownKeys()会返回所有属性key

   var obj = {

  1. a: 1,
  2. b: 2
  3. }
  4. Object.defineProperty(obj, 'method', {
  5. value: function () {
  6. alert("Non enumerable property")
  7. },
  8. enumerable: false
  9. })
  10. console.log(Object.keys(obj))
  11. // ["a", "b"]
  12. console.log(Reflect.ownKeys(obj))
  13. // ["a", "b", "method"]

  注意

  总结 对象方法遍历基本属性遍历原型链遍历不可枚举属性遍历Symbol

  for in

  是

  是

  否

  否

  Object.keys()

  是

  否

  否

  否

  Object.getOwnPropertyNames()

  是

  否

  是

  否

  Object.getOwnPropertySymbols()

  否

  js遍历数组的方法_js 对象数组遍历_js 遍历 对象数组

  否

  是

  是

  Object.getOwnPropertySymbols()

  是

  否

  是

  是

  三 其他遍历方法 1. for

  for循环是应该是最常见的循环方式了,它由三个表达式组成,分别是声明循环变量、判断循环条件、更新循环变量。这三个表达式用分号分隔。可以使用临时变量将数组的长度缓存起来,避免重复获取数组长度,当数组较大时优化效果会比较明显。

   const arr = [1,2,3,4,5]

  1. for(let i = 0, len = arr.length; i {
  2. setTimeout(function () {
  3. resolve(time)
  4. },time)
  5. })
  6. }
  7. async function test () {
  8. let arr = [Gen(2000),Gen(100),Gen(3000)]
  9. for await (let item of arr) {
  10. console.log(Date.now(),item)
  11. }
  12. }
  13. test()

  输出结果:

   function Gen (time) {

  1. return new Promise((resolve,reject) => {
  2. setTimeout(function () {
  3. resolve(time)
  4. },time)
  5. })
  6. }
  7. // async function test () {
  8. let arr = [Gen(2000),Gen(100),Gen(3000)]
  9. for (let item of arr) {
  10. console.log(Date.now(),item)
  11. }
  12. // }
  13. // test()

  输出结果:

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1746
0 评论
795

发表评论

!