js数组中indexOf/filter/forEach/map/reduce详解
今天在网上看到一篇帖子,如题:
出处:前端开发博客 (http://caibaojian.com/5-array-methods.html)
在ES5中一共有9个Array方法,分别是:
Array.prototype.indexOf
Array.prototype.lastIndexOf
Array.prototype.every
Array.prototype.some
Array.prototype.forEach
Array.prototype.map
Array.prototype.filter
Array.prototype.reduce
Array.prototype.reduceRight
1) indexOf
indexOf()方法返回在该数组中第一个找到的元素位置,如果它不存在则返回-1。
via不使用indexOf时原文来自:http://caibaojian.com/5-array-methods.html
var arr = ['apple','orange','pear'],
found = false; for(var i= 0, l = arr.length; i< l; i++){
if(arr[i] === 'orange'){
found = true;
}
} console.log("found:",found);
使用后
var arr = ['apple','orange','pear'];
console.log("found:", arr.indexOf("orange") != -1);
2) filter
该filter()方法创建一个新的匹配过滤条件的数组。
不用 filter() 时
var arr = [
{"name":"apple", "count": 2},
{"name":"orange", "count": 5},
{"name":"pear", "count": 3},
{"name":"orange", "count": 16},
]; var newArr = []; for(var i= 0, l = arr.length; i< l; i++){
if(arr[i].name === "orange" ){
newArr.push(arr[i]);
}
} console.log("Filter results:",newArr);
用了 filter():
var arr = [
{"name":"apple", "count": 2},
{"name":"orange", "count": 5},
{"name":"pear", "count": 3},
{"name":"orange", "count": 16},
]; var newArr = arr.filter(function(item){
return item.name === "orange";
}); console.log("Filter results:",newArr);
3) forEach()
forEach为每个元素执行对应的方法
var arr = [1,2,3,4,5,6,7,8]; // Uses the usual "for" loop to iterate
for(var i= 0, l = arr.length; i< l; i++){
console.log(arr[i]);
} console.log("========================"); //Uses forEach to iterate
arr.forEach(function(item,index){
console.log(item);
});
forEach是用来替换for循环的
4) map()
map()对数组的每个元素进行一定操作(映射)后,会返回一个新的数组,
不使用map
var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
function getNewArr(){
var newArr = [];
for(var i= 0, l = oldArr.length; i< l; i++){
var item = oldArr[i];
item.full_name = [item.first_name,item.last_name].join(" ");
newArr[i] = item;
}
return newArr;
}
console.log(getNewArr());
使用map后
var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
function getNewArr(){
return oldArr.map(function(item,index){
item.full_name = [item.first_name,item.last_name].join(" ");
return item;
});
}
console.log(getNewArr());
map()是处理服务器返回数据时是一个非常实用的函数。
5) reduce()
reduce()可以实现一个累加器的功能,将数组的每个值(从左到右)将其降低到一个值。
说实话刚开始理解这句话有点难度,它太抽象了。
场景: 统计一个数组中有多少个不重复的单词
不使用reduce时
var arr = ["apple","orange","apple","orange","pear","orange"];
function getWordCnt(){
var obj = {};
for(var i= 0, l = arr.length; i< l; i++){
var item = arr[i];
obj[item] = (obj[item] +1 ) || 1;
}
return obj;
}
console.log(getWordCnt());
使用reduce()后
//code from http://caibaojian.com/5-array-methods.html
var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){
return arr.reduce(function(prev,next){
prev[next] = (prev[next] + 1) || 1;
return prev;
},{});
} console.log(getWordCnt());
让我先解释一下我自己对reduce的理解。reduce(callback, initialValue)会传入两个变量。回调函数(callback)和初始值(initialValue)。假设函数它有个传入参数,prev和next,index和array。prev和next你是必须要了解的。
一般来讲prev是从数组中第一个元素开始的,next是第二个元素。但是当你传入初始值(initialValue)后,第一个prev将是initivalValue,next将是数组中的第一个元素。
比如:
/*
* 二者的区别,在console中运行一下即可知晓
*/ var arr = ["apple","orange"]; function noPassValue(){
return arr.reduce(function(prev,next){
console.log("prev:",prev);
console.log("next:",next); return prev + " " +next;
});
}
function passValue(){
return arr.reduce(function(prev,next){
console.log("prev:",prev);
console.log("next:",next); prev[next] = 1;
return prev;
},{});
}
最后感谢大神的指点;
出处:前端开发博客 (http://caibaojian.com/5-array-methods.html)
js数组中indexOf/filter/forEach/map/reduce详解的更多相关文章
- JS Array常用方法indexOf/filter/forEach/map/reduce详解
Array共有九个方法 Array.prototype.indexOf Array.prototype.lastIndexOf Array.prototype.every Array.protot ...
- 5个现在就该使用的数组Array方法: indexOf/filter/forEach/map/reduce详解(转)
ECMAScript5标准发布于2009年12月3日,它带来了一些新的,改善现有的Array数组操作的方法.然而,这些新奇的数组方法并没有真正流行起来的,因为当时市场上缺乏支持ES5的浏览器. ...
- JS数组中every(),filter(),forEach(),map(),some()方法学习笔记!
ES5中定义了五种数组的迭代方法:every(),filter(),forEach(),map(),some(). 每个方法都接受两个参数:要在每一项运行的函数(必选)和运行该函数的作用域的对象-影响 ...
- 怎样理解js数组中indexOf()的用法与lastIndexOf
第一首先你运行一下它的js代码: var arr1=["大学","中庸","论语","孟子","诗" ...
- js数组和对象相等判断、拷贝详解(结合几个现象讲解引用数据类型的趣事)
序言 最近遇到几个js引用数据类型造成的bug,今天结合bug详细分析一下,避免以后再犯,也希望能帮大家提个醒,强化js基本功. 目录 1.浅拷贝.深拷贝,解决变量赋值相互影响问题 2.判断2个数组. ...
- js数组中的find(), findIndex(), filter(), forEach(), some(), every(), map(), reduce()方法的详解和应用实例
1. find()与findIndex() find()方法,用于找出第一个符合条件的数组成员.它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该 ...
- python中的filter、map、reduce、apply用法
1. filter 功能: filter的功能是过滤掉序列中不符合函数条件的元素,当序列中要删减的元素可以用某些函数描述时,就应该想起filter函数. 调用: filter(function,seq ...
- 统计js数组中奇数元素的个数
如何统计一个JS数组中奇数元素的个数呢? 这是群友提出的一个问题,大部分群友给出的是遍历 然后对2取模,得到最终结果. 这样的写法是最容易想得到的,那么有没有其他思路呢? 这里我提供另外一种思路,我们 ...
- Jquery遍历筛选数组的几种方法和遍历解析json对象|Map()方法详解
Jquery遍历筛选数组的几种方法和遍历解析json对象|Map()方法详解 一.Jquery遍历筛选数组 1.jquery grep()筛选遍历数组 $().ready( function(){ v ...
随机推荐
- PHP 模拟 HTTP 基本认证(Basic Authentication)
当某个页面需要认证才能进行访问时,接到请求后服务器端会在响应头中发送一个 WWW-Authenticate 首部(用来标识认证安全域),语法为 WWW-Authenticate:Basic relam ...
- php中json_decode返回数组或对象
http://www.3lian.com/edu/2014/02-11/128395.html 1.json_decode() json_decode (PHP 5 >= 5.2.0, PECL ...
- 【转】WiFi基础知识
http://blog.csdn.net/myarrow/article/details/7930131 1. IE802.11简介 标准号 IEEE 802.11b IEEE 802.11a IEE ...
- Full exploitation of a cluster hardware configuration requires some enhancements to a single-system operating system.
COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION Operating System Desi ...
- ORM系列之二:EF(3) 数据库连接
目录 1.前言 2.Code First默认连接 3.Code First指定数据库 4.自定义连接 前言 在介绍EF的Code First模式时候,我们没有修改任何配置,运行之后自动在LocalDb ...
- ax Mail
SysMailer mailer = new SysMailer(); SysEmailParameters parameters = SysEmailParameters::find(); ; tr ...
- Spring 核心框架体系结构
转载:http://www.admin10000.com/document/10447.html 很多人都在用spring开发java项目,但是配置maven依赖的时候并不能明确要配置哪些spring ...
- Oracle 遇到的问题 (1)
1.ORA-01502:索引'DBEPMS.SYS_C009390'或这类索引的分区处于不可用状态 解决方法:[注 索引命名规则 IX_表名简称_列名简称/IX_表名简称_序号(索引长度在30字符以内 ...
- DOM中文本节点索引方法
问题 对于 jquery 接口text()只能取到有标签的 dom对象中 文本内容. 如果索引对象本身就是文本节点,则不好索引到, 没有相关的索引选择器. 例如: 对于<input>aaa ...
- jQuery 跨域访问的三种方式 No 'Access-Control-Allow-Origin' header is present on the reque
问题: XMLHttpRequest cannot load http://v.xxx.com. No 'Access-Control-Allow-Origin' header is present ...