javascript的Array对象的几个方法

javaScript的几个Array的操作方法,类似lambda的表达式

  1. map:对数组中的每一个值进行操作,返回值是 数组

    语法: array1.map(callbackfn[, thisArg])
    array1:必须的,一个数组对象

    callbackfn:必须的,最多接受 3个参数The map method calls the callbackfn function one time for each element in the array.

    thisArg:可选的,An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as thethis value.

    参照:https://msdn.microsoft.com/zh-CN/library/ff679976(v=vs.94).aspx

    function callbackfn(value, index, array1)

     

    回调参数

    定义

    value

    数组元素的值。

    index

    数组元素的数字索引。

    array1

    包含该元素的数组对象。

 var arr = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
 ];
 var a2 = arr.map(function(s){ return s.length});//[8,6,7,10]
 //(param1, param2, paramN) => expression
 // equivalent to:  => { return expression; }
 var a3 = arr.map(s => s.length);//[8,6,7,10]

2.filter:返回数组中的满足回调函数中指定的条件的元素,返回值是 数组

语法

array1.filter(callbackfn[, thisArg])
array1    必需。一个数组对象。    
callbackfn    必需。一个接受最多三个参数的函数。对于数组中的每个元素,filter 方法都会调用 callbackfn 函数一次。    
thisArg    可选。可在 callbackfn 函数中为其引用 this 关键字的对象。如果省略 thisArg,则 undefined 将用作 this 值。
 var arr2 = [5, 6, 13, 0, 1, 18, 23];
 //选出数组中的 偶数
 var even = arr2.filter(v => v%2 == 0);//[6,0,18];

参照:https://msdn.microsoft.com/zh-cn/library/ff679973(v=vs.94).aspx

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

语法:

array1.reduce(callbackfn[, initialValue])

array1:必须的,是一个数组对象

callbackfn:必须的,是一个回调函数,最多接收4个参数,The reduce method calls the callbackfn function one time for each element in the array.

initialValue:可选的, If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

参照:https://msdn.microsoft.com/zh-cn/library/ff679975(v=vs.94).aspx

var arr2 = [5, 6, 13, 0, 1, 18, 23];
 var sum = arr2.reduce((a,b) => a+b); //sum:66

转载于:https://my.oschina.net/u/1451372/blog/540150

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值