资讯专栏INFORMATION COLUMN

Javascript各种数组遍历方法归纳总结和兼容写法

Sanchi / 3477人阅读

摘要:主要用于枚举对象数组遍历效率最低的方法。当前数组元素的值。传递给函数的初始值注意对于空数组是不会执行回调函数的。

前言

PS: 2018/04/26 优化一下排版,重新梳理一下方法,补充一些信息,删除JQuery库用法,只讲解Javascript自带的,

for in

语句用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。主要用于枚举对象, 数组遍历效率最低的方法。

var ary = [1, 2, 3],
    obj = {
        name: "Tom",
        age: 18
    },
    i;

for (i in ary) {
    console.log(i);
}

for (i in obj) {
    console.log(obj[i]);
}

注意:
1, 遍历数组时, i表示当前索引值,ary[i]对应的元素遍历对象时, i表示key值, obj[i]表示key值对应的value值;
2, 跳出循环的方式有如下几种:return 函数执行被终止, break 循环被终止, continue 循环被跳过;

缺点:
1, 遍历所有属性包括原型链;
2, 忽略 enumerable 为 false 的属性;

//构造函数
function Person() {
  this.name = "mike";
};
//原型链属性
Person.prototype.age = 18;

//实例赋值
var mike = new Person,
  i;
mike.sex = "man";
mike.height = "180";

//设置不可枚举
Object.defineProperty(mike, "height", {
  enumerable: false
});

for (i in mike) {
  console.log(mike[i]);
}

优化方案:
hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象。不过需要注意的是, 此方法无法检查该对象的原型链中是否具有该属性, 该属性必须是对象本身的一个成员;

//构造函数
function Person() {
  this.name = "mike";
};
//原型链属性
Person.prototype.age = 18;

//实例赋值
var mike = new Person,
  i;
mike.sex = "man";

for (i in mike) {
  //过滤出对象自身的属性
  if (mike.hasOwnProperty(i)) {
    console.log(mike[i]);
  }
}       

注意: 这里依然会遍历所有属性,只是过滤出操作属性而已

For

循环可以将代码块执行指定的次数。

var ary = [1, 2, 3],
  i = 0,
  len = ary.length;

for (; i < len; i++) {
  console.log(ary[i]);
}

注意:
1, (如果使用var声明的话),for循环中的i在循环结束之后依然存在于作用域中, 为了避免影响作用域中的其他变量, 通常使用闭包或其他方式做处理
2, 避免使用for(var i=0, len = ary.length;i < len; i++){} 的方式, 数组长度每次循环都被计算, 效率低。将变量声明放在for的前面来执行
3, 跳出循环的方式有如下几种:return 函数执行被终止, break 循环被终止, continue 循环被跳过;

有种稍高逼格写法:

var ary = [1, 2, 3],
  i = ary.length - 1;

for (; i <= 0; i--) {
  console.log(ary[i]);
}

不考虑顺序情况下还不错,少一个变量并且能唬到一些新手

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

按照原始数组元素顺序依次处理元素.

参数 描述
function(currentValue, index, arr) 匿名函数,默认传参第1个是遍历的数组内容;第2个是对应的数组索引, 第3个是数组本身
thisValue 可选。对象作为该执行回调时使用, 传递给函数, 用作 "this" 的值。如果省略了 thisValue , "this" 的值为 "undefined"

注意: forEach() 对于空数组是不会执行回调函数的。

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];

ary.forEach(function (_ele, _index, _ary) {
  console.log(_ele, _index, _ary);
})

// 1 0 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 2 1 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 3 2 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 4 3 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 5 4 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 6 5 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 7 6 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 8 7 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 9 8 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
简单实现兼容写法:
Array.prototype._forEach = function (callback, context) {
  //指定指向, 默认window
  context = context || window;
  //浏览器支持直接调用方法, 终止后续操作
  if ("forEach" in Array.prototype) {
    this.forEach(callback, context);
    return;
  }
  //保证回调函数
  if (typeof callback !== "function") throw "callback must be a function"

  //遍历数组, 设置指向
  var i = 0,
    len = this.length;
  for (; i < len; i++) {
    callback.call(context, this[i], i, this)
  }
}

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
ary._forEach(function (_ele, _index, _ary) {
  console.log(_ele, _index, _ary);
})
map(function(currentValue,index,arr), thisValue)

按照原始数组元素顺序依次处理元素并返回一个新数组, 数组中的元素为原始数组元素调用函数处理后的值。

参数 描述
function(currentValue, index, arr) 匿名函数,默认传参第1个是遍历的数组内容;第2个是对应的数组索引, 第3个是数组本身
thisValue 可选。对象作为该执行回调时使用, 传递给函数, 用作 "this" 的值。如果省略了 thisValue , "this" 的值为 "undefined"

注意: map() 对于空数组是不会执行回调函数的。

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var _ary = ary.map(function (_ele, _index, _ary) {
  console.log(_ele, _index, _ary);
  return _ele * 2
})
console.log("原数组: " + ary);
console.log("返回数组: " + _ary);

// 1 0 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 2 1 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 3 2 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 4 3 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 5 4 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 6 5 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 7 6 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 8 7 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 9 8 [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// 原数组: 1,2,3,4,5,6,7,8,9
// 返回数组: 2,4,6,8,10,12,14,16,18
简单实现兼容写法:
Array.prototype._map = function (callback, context) {
  //指定指向, 默认window
  context = context || window;
  //浏览器支持直接调用方法, 终止后续操作
  if ("map" in Array.prototype) {
    return this.map(callback, context);
  }
  //保证回调函数
  if (typeof callback !== "function") throw "callback must be a function"

  //遍历数组, 返回操作过的数组
  var _ary = [],
    i = 0,
    len = this.length;
  for (; i < len; i++) {
    _ary[i] = callback.call(context, this[i], i, this);
  }
  return _ary;
}

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9],
  _ary = ary._map(function (_ele, _index, _ary) {
    return _ele * 10
  });
console.log("原数组: " + ary);
console.log("返回数组: " + _ary); 
filter(function(currentValue,index,arr), thisValue)

使用指定的函数测试所有元素, 并创建一个包含所有通过测试的元素的新数组。

参数 描述
function(currentValue, index, arr) 匿名函数,默认传参第1个是遍历的数组内容;第2个是对应的数组索引, 第3个是数组本身
thisValue 可选。对象作为该执行回调时使用, 传递给函数, 用作 "this" 的值。如果省略了 thisValue , "this" 的值为 "undefined"

注意: filter() 对于空数组是不会执行回调函数的。

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9],
  _ary = ary.filter(function (_ele, _index, _ary) {
    return _ele < 5
  });
console.log("原数组: " + ary);
console.log("返回数组: " + _ary);

// 原数组: 1,2,3,4,5,6,7,8,9
// 返回数组: 1,2,3,4
简单实现兼容写法:
Array.prototype._filter = function (callback, context) {
  //指定指向, 默认window
  context = context || window;
  //浏览器支持直接调用方法, 终止后续操作
  if ("filter" in Array.prototype) {
    return this.filter(callback, context);
  }
  //保证回调函数
  if (typeof callback !== "function") throw "callback must be a function"

  //遍历数组, 返回操作过的数组
  var _ary = [],
    i = 0,
    len = this.length;
  for (; i < len; i++) {
    if (callback.call(context, this[i], i, this)) {
      _ary.push(this[i])
    }
  }
  return _ary;
}

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9],
  _ary = ary._filter(function (_ele, _index, _ary) {
    return _ele & gt; 3
  });
console.log("原数组: " + ary);
console.log("返回数组: " + _ary);
every(function(currentValue,index,arr), thisValue)

用于检测数组所有元素是否都符合指定条件,返回布尔值.

参数 描述
function(currentValue, index, arr) 匿名函数,默认传参第1个是遍历的数组内容;第2个是对应的数组索引, 第3个是数组本身
thisValue 可选。对象作为该执行回调时使用, 传递给函数, 用作 "this" 的值。如果省略了 thisValue , "this" 的值为 "undefined"

注意: every() 对于空数组是不会执行回调函数的。

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9],
  bol = ary.every(function (_ele, _index, _ary) {
    return _ele < 5
  });
console.log(bol); // false
简单实现兼容写法:
Array.prototype._every = function (callback, context) {
  //指定指向, 默认window
  context = context || window;
  //浏览器支持直接调用方法, 终止后续操作
  if ("every" in Array.prototype) {
    return this.every(callback, context);
  }
  //保证回调函数
  if (typeof callback !== "function") throw "callback must be a function"

  //遍历数组, 返回操作过的数组
  var _ary = [],
    i = 0,
    len = this.length;
  for (; i < len; i++) {
    if (callback.call(context, this[i], i, this)) {
      return false;
    }
  }
  return true;
}

var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9],
  bol = ary._every(function (_ele, _index, _ary) {
    return _ele & gt; 5
  });
console.log(bol);
reduce/reduceRight(function(previousValue, currentValue, currentIndex, array), initialValue)

reduce对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果, 并且此返回值在下一次调用该回调函数时作为参数提供。
reduceRight反向操作.

参数 描述
function(previousValue, currentValue, currentIndex, array) previousValue:通过上一次调用回调函数获得的值。如果向 reduce 方法提供 initialValue, 则在首次调用函数时, previousValue 为 initialValue。currentValue:当前数组元素的值。currentIndex:当前数组元素的数字索引。array:包含该元素的数组对象。
initialValue 可选。传递给函数的初始值,

注意: reduce() 对于空数组是不会执行回调函数的。

先来打印看看里面的传参和没初始值的情况:

var ary = [1, 2, 3, 4],
  sum = ary.reduce(function (previousValue, currentValue, currentIndex, array) {
    console.log(previousValue, currentValue, currentIndex, array);
    return previousValue + currentValue
  });

console.log(sum);
// 1 2 1 [ 1, 2, 3, 4 ]
// 3 3 2 [ 1, 2, 3, 4 ]
// 6 4 3 [ 1, 2, 3, 4 ]
// 10
var ary = [1, 2, 3, 4],
  sum = ary.reduce(function (previousValue, currentValue, currentIndex, array) {
    console.log(previousValue, currentValue, currentIndex, array);
    return previousValue + currentValue
  }, 10);

console.log(sum);
// 10 1 0 [ 1, 2, 3, 4 ]
// 11 2 1 [ 1, 2, 3, 4 ]
// 13 3 2 [ 1, 2, 3, 4 ]
// 16 4 3 [ 1, 2, 3, 4 ]
// 20

两者区别在于多了一层运算,文档说明如下
在第一次调用回调函数时, 作为参数提供的值取决于 reduce 方法是否具有 initialValue 参数。
1, 有:

1) previousValue 参数为 initialValue。
2) currentValue 参数是数组中的第一个元素的值。

2, 没有:

1) previousValue 参数是数组中的第一个元素的值。
2) currentValue 参数是数组中的第二个元素的值。

简单实现兼容写法:
Array.prototype._reduce = function (callback, initValue) {
  //浏览器支持直接调用方法, 终止后续操作
  if ("reduce" in Array.prototype) {
    this.reduce(callback, context);
    return;
  }
  //保证回调函数
  if (typeof callback !== "function") throw "callback must be a function"

  //遍历数组, 设置指向
  var add = initValue || this.unshift(initValue),
    i = 0,
    len = this.length;
  for (; i < len; i++) {
    add = callback.call(null, add, this[i], i, this)
  }
}

var ary = [1, 2, 3, 4],
  sum = ary.reduce(function (previousValue, currentValue, currentIndex, array) {
    return previousValue + currentValue
  }, 20);
console.log(sum);
entries(), keys()和values()

它们都返回一个遍历器对象,可以用for...of循环进行遍历, 唯一的区别是keys()是对键名/索引值的遍历、values()是对键值的遍历, entries()是对键/索引值值对的遍历

var ary = [1, 2, 3, 4];
for (let elem of ary.keys()) {
  console.log(elem);
}
for (let elem of ary.values()) {
  console.log(elem);
}
for (let elem of ary.entries()) {
  console.log(elem);
}

写到这里就差不多了,ES5还有壹些筛选方法例如find(), includes()等其实都是大同小异就不继续写了,ES6还会涉及到叠代器的知识点,大家有兴趣自行研究吧.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/106245.html

相关文章

  • 谈一谈几种处理JavaScript异步操作的办法

    摘要:问题是处理完了,却也引发了自己的一些思考处理的异步操作,都有一些什么方法呢一回调函数传说中的就是来自回调函数。而回调函数也是最基础最常用的处理异步操作的办法。 引言 js的异步操作,已经是一个老生常谈的话题,关于这个话题的文章随便google一下都可以看到一大堆。那么为什么我还要写这篇东西呢?在最近的工作中,为了编写一套相对比较复杂的插件,需要处理各种各样的异步操作。但是为了体积和兼容...

    曹金海 评论0 收藏0
  • JavaScript知识架构学习路径(一)- 变量篇

    摘要:在此,我们首先根据变量的作用域,将变量划分为三级,具体是全局变量局部变量和参数变量。 【摘要】本文是专为JavaScript入门者而总结的,总体上将JavaScript的基础部分分成了九大块,分别是变量、运算符、数组、流程控制结构、字符串函数、函数基础、DOM操作基础、文档对象模型DOM和正则表达式。 【关键字】变量、运算符、数组、流程控制结构、函数、DOM、正则表达式。 本篇文章的主...

    toddmark 评论0 收藏0
  • js基础归纳总结1

    摘要:局部变量在函数中声明的变量,会成为函数的局部变量。局部变量的作用域是局部的只能在函数内部访问它们。单独的情况下,指的是全局对象。在事件中,指的是接收事件的元素。布尔值提供一种布尔数据类型。所有不具有真实值的即为布尔值为零负零空值。 闭包 闭包的优点:1.可以读取函数内部的变量2.这些变量的值始终保持在内存中适用场景 作用域 作用域指的是有权访问的变量集合。在 JavaScript 中有...

    Jeff 评论0 收藏0
  • WEB开发面面谈之(5)——写JS时必须注意的的一些问题

    摘要:更多详情请看下面例举了日常前段开发中遇到的场景,解决方案有很多,但从开发阶段就进行规范,可以很大程度避免很多后续的潜在和兼容问题。 更多详情请看http://blog.zhangbing.club/%E... 下面例举了日常前段开发中遇到的场景,解决方案有很多,但从开发阶段就进行规范,可以很大程度避免很多后续的潜在和兼容问题。 获取body元素 非标准做法 document.body ...

    nihao 评论0 收藏0
  • 前端基础入门五(掌握jQuery的常用api,实现动态效果)

    摘要:基本概念学习目标学会如何使用,掌握的常用,能够使用实现常见的效果。想要实现简单的动画效果,也很麻烦代码冗余。实现动画非常简单,而且功能更加的强大。注意选择器返回的是对象。 jQuery基本概念 学习目标:学会如何使用jQuery,掌握jQuery的常用api,能够使用jQuery实现常见的效果。 为什么要学习jQuery? 【01-让div显示与设置内容.html】 使用javasc...

    nevermind 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<