做前端有多年了,看过不少技术文章,学了新的技术,但更新迭代快的大前端,庞大的知识库,很多学过就忘记了,特别在项目紧急的条件下,哪怕心中隐隐约约有学过一个方法,但会下意识的使用旧的方法去解决,多年前ES5几个新增的数组方法,好用但是常忘记用,趁着这周比较清闲,重温下并做下笔记,养成记笔记的好习惯。

forEach

forEach是ES5的Array方法中用得最频繁的一个,就是遍历,循环输出,它接受一个必须的回调函数作为参数。

let arr1 = [1,2,3,4]
arr1.forEach((item)=>{
console.info(item);
})
//
//
//
//

等同于传统的for循环。

let arr1 = [1,2,3,4]
for(let i = 1;i<arr1.length;i++){
console.info(arr1[i])
}
//
//
//
//

相比for循环,forEach简洁了很多,forEach方法中的回调函数支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身。

[].forEach((value, index, array)=> {
});

举个例子:

let array1 = [1, 2, 3, 4]
let array2 =[]; array1.forEach( (item, index, array) => {
console.info(array1 === array);//(4)true
array2[index] = item * item;
}); console.info(array2);// [1, 4, 9, 16]

forEach除了接受一个回调函数作为参数,还接受一个可选的上下文参数(改变回调函数里面的this指向)。

array.forEach(callback,[thisObject])

例子,obj.consoleFn被调用后,this指向了obj。

let obj = {
nameArr: ["猫", "狗", "羊","鸟"],
isCat: function (name) {
return /^猫/.test(name);
},
consoleFn: function (name) {
if (this.isCat(name)) {
console.info(`你是${name}`);
} else {
console.info(`你不是${name}`);
}
}
} obj.nameArr.forEach(obj.consoleFn,obj);
// 你是猫
// 你不是狗
// 你不是羊
// 你不是鸟

下面的例子obj.consoleFn作为forEach的参数后被调用,此时如果没有指定forEach的上下文参数,那么obj.consoleFn中this指向window,会导致页面报错。这里要了解this的知识,可以查看这篇文章《javascript笔记之this用法》。

如下代码,window下并没有isCat函数,所以会出现报错。

let obj = {
nameArr: ["猫", "狗", "羊","鸟"],
isCat: function (name) {
return /^猫/.test(name);
},
consoleFn: function (name) {
if (this.isCat(name)) {
console.info(`你是${name}`);
} else {
console.info(`你不是${name}`);
}
}
} obj.nameArr.forEach(obj.consoleFn);// Uncaught TypeError: this.isCat is not a function

forEach不会遍历空元素

let array3 = [1,,3]
console.info(array3.length); //
array3.forEach((item)=>{
console.info(item);
});
//
//

map

map是ES5的Array方法中最基本的一个,其基本用法跟forEach类似,也是遍历,不同是的最终输出一个新的数组

array.map(callback,[thisObject]);

callback的参数跟forEach一样。

array.map(function(value, index, array) {
//callback需要有return值
});

map函数是把原数组被“映射”成一个新数组

let array1 = [1, 2, 3, 4]
let array2 = array1.map( (item, index, array) => {
return item * item
}); console.info(array2); // [1,4,9,16]

filter

filter为“过滤”、“筛选”之意。指数组通过filter后,返回过滤后的新数组。

array.filter(callback,[thisObject]);

filter的callback函数需要返回布尔值true或false(返回值只要是弱等于== true/false就可以了),callback需要有return值

比如,下面数组中array4的前2个组返回0和false则被过滤掉。

const array4 = [0, false, 2, 3];
const array5 = array4.filter(function(item) {
return item;
});
console.info(array5); // [2, 3]

再来一个例子,把数组中的猪过滤掉。

const array6 = ["猫", "狗", "羊", "猪"];
const array7 = array6.filter(function(item) {
if(item == '猪') return false
else return item
});
console.info(array7); // ["猫", "狗", "羊"]

some

some意指“某些”,指是否“某些项”合乎条件。用法如下:

array.some(callback,[thisObject]);

some要求至少有1个值让callback返回true就可以了,如下例子:

const arrFraction = [60, 80, 95, 70];
const passFraction = 90;//有一个人高于90分就通过入学考试 const result = arrFraction.some((item)=>{return item > passFraction
})
if(result){
console.info("通过入学考试");
}

every

every意指“每一项”,指所有必须合乎条件,只要一项不符合则返回false。用法如下:

const arrFraction = [91, 93, 95, 89];
const passFraction = 90;//所有人高于90分就通过入学考试 const result = arrFraction.every((item)=>{
return item > passFraction
})
if(result){
console.info("通过入学考试");
}else{
console.info("不通过入学考试");
}

reduce

reduce意指“缩减”,它接收一个函数作为累加器,对数组中的每个值从左到右遍历进行操作,最终计算为一个值。用法如下:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
//total 必需。初始值, 或者计算结束后的返回值
//currentValue 必需。当前元素
//currentIndex 可选。当前元素的索引
//arr 可选。当前元素所属的数组对象。
//initialValue 可选。传递给函数的初始值,也就是total的初始值

比如,求数组项之和,初始值为0,下面代码从0开始加到6:

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

let sum = arr.reduce(function (total, currentValue) {
return total + currentValue;
},0);
console.info(sum)

比如,求数组的最小值

const arr = [20,20,35,4,15,6];

let min= arr.reduce(function (prev, cur) {
return Math.min(prev,cur);
});
console.info(min)

reduceRight

reduceRight() 方法的功能和reduce功能是一样的,不同的是遍历的顺序相反,它是从数组的最后一项开始,向前遍历到第一项

【原】javascript笔记之Array方法forEach&map&filter&some&every&reduce&reduceRight的更多相关文章

  1. js数组方法forEach,map,filter,every,some实现

    Array.prototype.map = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "fun ...

  2. ES6新增的常用数组方法(forEach,map,filter,every,some)

    ES6新增的常用数组方法 let arr = [1, 2, 3, 2, 1]; 一 forEach => 遍历数组 arr.forEach((v, i) => { console.log( ...

  3. ES6 数组方法 forEach map filter find every some reduce

    1. forEach const colors = ['red', 'blue', 'green'] colors.forEach(function (params) { console.log(pa ...

  4. 5个数组Array方法: indexOf、filter、forEach、map、reduce使用实例

    ES5中,一共有9个Array方法 Array.prototype.indexOf Array.prototype.lastIndexOf Array.prototype.every Array.pr ...

  5. ES5 的 forEach, map, filter, some, every 方法

    1:  forEacharray.forEach(callback,[ thisObject]) // 遍历数组里面的所有数字// item 是值, i 是序号, array 是整个数组 [1, 2 ...

  6. JavaScript中数组Array方法详解

    ECMAScript 3在Array.prototype中定义了一些很有用的操作数组的函数,这意味着这些函数作为任何数组的方法都是可用的. 1.Array.join()方法 Array.join()方 ...

  7. js Array 中的 map, filter 和 reduce

    原文中部分源码来源于:JS Array.reduce 实现 Array.map 和 Array.filter Array 中的高阶函数 ---- map, filter, reduce map() - ...

  8. 数组的新方法 forEach some filter findIndex

    forEach  some  filter  findIndex这些都属于数组的新方法,都会对数组中的每一项,进行遍历,执行相关的操作: 只不过在循环的时候有些不一样 参考资料:https://wan ...

  9. 处理数组的forEach map filter的兼容性

    处理数组的forEach //forEach处理 if(!Array.prototype.forEach) { Array.prototype.forEach = function (callback ...

随机推荐

  1. ADC0832的应用

    ADC0832是美国国家半导体公司生产的一种8位逐次比较型CMOS双通道A-D转换器,采用5V电源电压供电,模拟电压输入范围为0~5V,内部时钟250KHz时转换速度为32微秒. 仿真图为: 程序为: ...

  2. CSS学习笔记五:display,position区别

    最近常用css,经常在位置方面使用导display与position这两个属性,所以想要弄清楚它们之间的意思. 一.display 作用是规定元素应该生成的框的类型.意思是定义建立布局时元素生成的显示 ...

  3. 由ping所引发的思考~

    今天看了掘金一片关于ping原理的文章,https://juejin.im/entry/5af8d5e651882565bd25581c?utm_source=gold_browser_extensi ...

  4. 在AspNetCore 中 使用Redis实现分布式缓存

    AspNetCore 使用Redis实现分布式缓存 上一篇讲到了,Core的内置缓存:IMemoryCache,以及缓存的基础概念.本篇会进行一些概念上的补充. 本篇我们记录的内容是怎么在Core中使 ...

  5. The JRE_HOME environment variable is not defined correctly

    启动Tomcat后startup.bat脚本调用了catalina.bat,然后catalina.bat调用了setclasspath.bat,setclasspath.bat的头部定义了JAVA_H ...

  6. css的input文本框的 propertychange、focus、blur

    1.输入框检查的需求--即时搜索--解决方案 当input的value发生变化就会发生,无论是键盘输入还是鼠标黏贴的改变都能及时监听到变化,propertychange,只要当前对象属性发生改变.(I ...

  7. Oracle中的优化问题

    1. 在查询时, 尽量使用列名; 2. 在子查询和多表查询都可以达到目的时, 尽量使用多表查询; 3. 在集合运算中, 如果集合中含有null, 那么不能用not in, 但可以用in(可以理解为nu ...

  8. Jacob工具类使用文件互转服务 word转html html转excel word转pdf excel转pdf ppt转pdf

    前提条件  必须安装MS office 1.jdk使用jdk1.8 2.jacob.dll放在..\jdk1.8\jre\bin目录下 3.eclipse的jre版本要和jdk一致,window-&g ...

  9. Vue数据双向绑定原理及简单实现

    嘿,Goodgirl and GoodBoy,点进来了就看完点个赞再go. Vue这个框架就不简单介绍了,它最大的特性就是数据的双向绑定以及虚拟dom.核心就是用数据来驱动视图层的改变.先看一段代码. ...

  10. 解决VMware虚拟机报错“无法连接MKS:套接字连接尝试次数太多,正在放弃”

    1.错误描述 在VMware中打开虚拟机时报错: "无法连接MKS:套接字连接尝试次数太多,正在放弃" 物理机操作系统: Windows 7 虚拟机操作系统: Kali Linux ...