ECMAScript5标准发布于2009年12月3日,它带来了一些新的,改善现有的Array数组操作的方法。然而,这些新奇的数组方法并没有真正流行起来的,因为当时市场上缺乏支持ES5的浏览器。
 
 

Array "Extras"

 
没有人怀疑这些方法的实用性,但写polyfill(PS:兼容旧版浏览器的插件)对他们来说是不值得的。它把“必须实现”变成了“最好实现”。有人居然将这些数组方法称之为Array "Extras"。哎!
 
但是,时代在变化。如果你看看Github上流行的开源JS项目,你会发现趋势正在转变。大家都想削减大量(第三方库)的依赖,仅用本地代码来实现。
 
好了,让我们开始吧。
 
我的5个数组
 
在ES5中,一共有9个Array方法 http://kangax.github.io/compat-table/es5/
 
注* 九个方法
 
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
 
我将挑选5种方法,我个人认为是最有用的,很多开发者都会碰到。
 

1) indexOf

 
indexOf()方法返回在该数组中第一个找到的元素位置,如果它不存在则返回-1。
 
不使用indexOf时
 
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()后
 
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;
    },{});
}
 
console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());
原文地址: colintoh.com

5个现在就该使用的数组Array方法: indexOf/filter/forEach/map/reduce详解(转)的更多相关文章

  1. js数组中indexOf/filter/forEach/map/reduce详解

    今天在网上看到一篇帖子,如题: 出处:前端开发博客 (http://caibaojian.com/5-array-methods.html) 在ES5中一共有9个Array方法,分别是: Array. ...

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

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

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

  4. JS数组中every(),filter(),forEach(),map(),some()方法学习笔记!

    ES5中定义了五种数组的迭代方法:every(),filter(),forEach(),map(),some(). 每个方法都接受两个参数:要在每一项运行的函数(必选)和运行该函数的作用域的对象-影响 ...

  5. go 数组(array)、切片(slice)、map、结构体(struct)

    一 数组(array) go语言中的数组是固定长度的.使用前必须指定数组长度. go语言中数组是值类型.如果将数组赋值给另一个数组或者方法中参数使用都是复制一份,方法中使用可以使用指针传递地址. 声明 ...

  6. JavaScript中数组Array方法详解

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

  7. JavaScript中的数组Array方法

    push(),pop()方法 push(),pop()方法也叫栈方法,push()可以理解成,向末尾推入,而pop()恰好相反,可以理解成从末尾移除(取得). var nums=[1,2,3,4]; ...

  8. JavaScript 数组(Array)方法汇总

    数组(Array)常用方法; 数组常用的方法:concat(),every(), filter(), forEach(),  indexOf(), join(), lastIndexOf(), map ...

  9. 如何让类数组也使用数组的方法比如:forEach()

    思路: 让类数组绑定数组的方法<div>1</div><div>2</div>方法一: let div = document.getElementsBy ...

随机推荐

  1. GammaRay is a tool to poke around in a Qt-application(确实很多功能)

    GammaRay is a tool to poke around in a Qt-application and also to manipulate the application to some ...

  2. Codeforces 449 B. Jzzhu and Cities

    堆优化dijkstra,假设哪条铁路能够被更新,就把相应铁路删除. B. Jzzhu and Cities time limit per test 2 seconds memory limit per ...

  3. MySQL - 常见的三种数据库存储引擎

    原文:MySQL - 常见的三种数据库存储引擎 数据库存储引擎:是数据库底层软件组织,数据库管理系统(DBMS)使用数据引擎进行创建.查询.更新和删除数据.不同的存储引擎提供不同的存储机制.索引技巧. ...

  4. HTTP协议(一些报头字段的作用,如cace-control、keep-alive)

    ---恢复内容开始--- Http连接是一种短连接,是一种无状态的连接. 所谓的无状态,是指浏览器每次向服务器发起请求的时候,不是通过一个连接,而是每次都建立一个新的连接. 如果是一个连接的话,服务器 ...

  5. 北大SQL数据库视频课程笔记

    Jim Gray - Transaction processing: concepts and techniqueshttp://research.microsoft.com/~gray/ 事务概念 ...

  6. Virtualization of iSCSI storage

    This invention describes methods, apparatus and systems for virtualization of iSCSI storage. Virtual ...

  7. P和P1指向了O和O1两个变量(对象)的地址, 而不是O和O1的内容(对象的实际地址)——充分证明@是取变量(对象)的地址,而不是变量里面的内容,够清楚!

    如图,为什么这样取出来的p,p1的值不一样呢?   165232328群友庾伟洪告诉我:  P和P1指向了O和O1两个变量(对象)的地址, 而不是O和O1的内容(对象的实际地址) ,你想P指向真正的对 ...

  8. Leetcode 136 Single Number 亦或

    题意就是从一堆数中找出唯一的一个只存在一个的数.除了那个数,其他的数都是两个相同的数. 通过亦或的性质: 1)a^a = 0 0^a = a 2)交换律 a^b = b^ a 3)结合律 (a^b)^ ...

  9. OpenGL图形渲染管线、VBO、VAO、EBO概念及用例

    图形渲染管线(Pipeline) 图形渲染管线指的是对一些原始数据经过一系列的处理变换并最终把这些数据输出到屏幕上的整个过程. 图形渲染管线的整个处理流程可以被划分为几个阶段,上一个阶段的输出数据作为 ...

  10. 零元学Expression Design 4 - Chapter 3 看小光被包围了!!如何活用「Text On Path」设计效果

    原文:零元学Expression Design 4 - Chapter 3 看小光被包围了!!如何活用「Text On Path」设计效果 本章将教大家如何活用「Text On Path」,做出文绕图 ...