JavaScript数组循环

一、前言

利用Javascript map(),reduce()和filter()数组方法可以遍历数组。而不是积累起来for循环和嵌套来处理列表和集合中的数据,利用这些方法可以更好地将逻辑组织成功能的构建块,然后将它们链接起来以创建更可读和更易于理解的实现。ES6也提供了一些更好的数组方法,比如.find,.findIndex,.of和for..of循环。

二、具体实现

1.数组循环

var officers = [s

{ id: 20, name: 'Captain' },

{ id: 24, name: 'General' },

{ id: 56, name: 'Admiral' },

{ id: 88, name: 'Commander' }

];

2.for循环,使用率最高,也是最基本的一种遍历方式

var officersIds = [];

for(var i=0,len=officers.length;i<len; i++){

officersIds.push(officers[i].id);

}

console.log(officersIds); // [20,24,56,88]

3.forEach循环

forEach中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)

var officersIds = [];

officers.forEach(function (officer,index,array) {

console.log(index); //0,1,2,3,

console.log(officer); //{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}

officersIds.push(officer.id);

});

console.log(officersIds); //[20,24,56,88]

4.for in循环

for...in循环可用于循环对象和数组,推荐用于循环对象,可以用来遍历JSON

var officersIds = [];

for(var key in officers){

console.log(key); // 0 1 2 3 返回数组索引

console.log(officers[key]); //{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}

officersIds.push(officers[key].id);

}

console.log(officersIds); //[20,24,56,88]

5.for of循环

可循环数组和对象,推荐用于遍历数组。

for...of提供了三个新方法:

key()是对键名的遍历;

value()是对键值的遍历;

entries()是对键值对的遍历;

let arr = ['科大讯飞', '政法BG', '前端开发'];

for (let item of arr) {

console.log(item); //  科大讯飞  政法BG  前端开发

}

// 输出数组索引

for (let item of arr.keys()) {

console.log(item);  // 0 1 2

}

// 输出内容和索引

for (let [item, val] of arr.entries()) {

console.log(item + ':' + val); //  0:科大讯飞  1:政法BG  2:前端开发

}

var officersIds = [];

for (var item of officers) {

console.log(item); //{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}

officersIds.push(item.id);

}

console.log(officersIds); // [20,24,56,88]

// 输出数组索引

for(var item of officers.keys()){

console.log(item); // 0 1 2 3

}

// 输出内容和索引

for (let [item, val] of officers.entries()) {

console.log(item) // 0 1 2 3 输出数组索引

console.log(val);//{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}

console.log(item + ':' + val);

}

6.map循环

map() 会返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

map() 方法按照原始数组元素顺序依次处理元素。

map 不修改调用它的原数组本身。

map()中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)

var arr = [

{name:'a',age:'18'},

{name:'b',age:'19'},

{name:'c',age:'20'}

];

arr.map(function(item,index) {

if(item.name == 'b') {

console.log(index)  // 1

}

})

7.filter

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

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

}, thisValue)

var designer = peoples.filter(function (people) {

return people.job === "designer";

});

组合使用

var totalScore = peoples

.filter(function (person) {

return person.isForceUser;

})

.map(function (choose) {

return choose.mathScore + choose.englishScore;

})

.reduce(function (total, score) {

return total + score;

}, 0);

Array.from()

var divs = document.querySelectorAll('div.pane');

var text = Array.from(divs, (d) => d.textContent);

console.log("div text:", text);

// Old, ES5 way to get array from arguments

function() {

var args = [].slice.call(arguments);

//...

}

// Using ES6 Array.from

function() {

var args = Array.from(arguments);

//..

}

var filled = Array.from([1,,2,,3], (n) => n || 0);

console.log("filled:", filled);

// => [1,0,2,0,3]

JavaScript数组循环的更多相关文章

  1. 手写js代码(一)javascript数组循环遍历之forEach

    注:原文地址http://blog.csdn.net/oscar999/article/details/8671546 我这里是仿照学习! 1.js的数组循环遍历 ①数组的遍历首先想到的是for()循 ...

  2. JavaScript数组循环遍历之forEach

    1.  js 数组循环遍历. 数组循环变量,最先想到的就是 for(var i=0;i<count;i++)这样的方式了. 除此之外,也可以使用较简便的forEach 方式 2.  forEac ...

  3. javaScript数组循环删除

    遍历数组循环的时候,限定条件不要写arr.length,因为数组的长度会随着删除元素的同时减小. 例如,一个原本长度为10的数组,如果采用 for(var i = 0; i< arr.lengt ...

  4. Javascript 数组循环遍历之forEach

    1.  js 数组循环遍历. 数组循环变量,最先想到的就是 for(var i=0;i<count;i++)这样的方式了. 除此之外,也可以使用较简便的forEach 方式   2.  forE ...

  5. JavaScript 基础数组循环和迭代的几种方法

    JavaScript 数组循环和迭代   (之前一直没怎么注意数组循环,今天做一道题时,用到forEach循环发现它并没有按照我想象的样子执行,总结一下数组循环) 一.第一种方法就是for()循环   ...

  6. JavaScript数组forEach循环

    JavaScript数组forEach循环 今天写JavaScript代码把forEach循环数组忘记写法了,在此记录一下以防止未来忘记. let a = [1, 2, 3]; a.forEach(f ...

  7. Javascript数组操作

    使用JS也算有段时日,然对于数组的使用,总局限于很初级水平,且每每使用总要查下API,或者写个小Demo测试下才算放心,一来二去,浪费不少时间:思虑下,堪能如此继续之?当狠心深学下方是正道. 原文链接 ...

  8. 也谈面试必备问题之 JavaScript 数组去重

    Why underscore (觉得这部分眼熟的可以直接跳到下一段了...) 最近开始看 underscore.js 源码,并将 underscore.js 源码解读 放在了我的 2016 计划中. ...

  9. javascript数组的知识点讲解

    javascript数组的知识点讲解 阅读目录 数组的基本方法如下 concat() join() pop() push() reverse() shift() sort() splice() toS ...

随机推荐

  1. Python之HTTP静态Web服务器开发

    众所周知,Http协议是基于Tcp协议的基础上产生的浏览器到服务器的通信协议 ,其根本原理也是通过socket进行通信. 使用HTTP协议通信,需要注意其返回的响应报文格式不能有任何问题. 响应报文, ...

  2. where 和having 的区别

    where : 约束声明,在查询结果返回之前对数据库中的查询条件进行约束    其后不能写聚合函数 having  过滤声明,在查询结果返回之后进行过滤,

  3. 翻转二叉树(深搜-先序遍历-交换Node)

    题目:翻转二叉树,例如 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 已知二叉树的节点定义如下: class TreeNode { in ...

  4. AQS系列(二)- ReentrantLock的释放锁

    前言 在AQS系列(一)中我们一起看了ReentrantLock加锁的过程,今天我们看释放锁,看看老Lea那冷峻的思维是如何在代码中笔走龙蛇的. 正文 追踪unlock方法: public void ...

  5. [TimLinux] Python学习内容框架

    以下内容主体来自<Python学习手册第四版>,大致整理出的方向 1. 第一部分:使用入门 介绍Python语法之前,先对Python的的各个方面进行一个比较宽广的介绍,包含对Python ...

  6. Codeforces 题解 CF863A 【Quasi-palindrome】

    此题本质上是:求一个数去掉后缀零后是否是回文串 因此,代码分为: >>> 读入 >>> 删除后缀0 >>> 判断回文 >>> 转 ...

  7. 搭建Squid3 密码账号IP代理

    上文中,说明了 Squid3 IP Proxy 隐藏原IP,这里就搭建Squid 3密码账号IP代理进行整理,涉及环境 Ubuntu 18.04. Step 1: htpasswd 和 htdiges ...

  8. 最全的防火墙(firewalld)

    第1章  防火墙的介绍 1.1  防火墙的介绍 1.1.1 概念 动态管理防火墙服务(图形界面和linux界面都可以实现) 支持不同防火墙的区域信息 属于传输层次的防火墙 1.1.2 防火墙的默认规则 ...

  9. 60%的人不懂Python进程Process,你懂吗?

    前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:蒋狗    新手注意:如果你Python基础学的不够扎实,遇问题没人解答 ...

  10. VS2013 MFC 库冲突引起的错误解决

    http://www.cnblogs.com/rainbowzc/archive/2010/06/29/1767248.html 7 1>LIBCMT.lib(crt0dat.obj) : er ...