js-数组操作与功能-运用

1 过滤数组 

  array.filter(function(currentValue,index,arr), thisValue)
 
currentValue 必须。当前元素的值
index 可选。当期元素的索引值
arr 可选。当期元素属于的数组对象
thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"
 

 

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

  注意: filter() 不会对空数组进行检测。

  注意: filter() 不会改变原始数组。

  1.1  [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object] 

data = [Object, Object]
data.filter((item, i) => { // 筛选出数组中对象id不等于‘201’或201的,并返回符合要求数组
       item.id != 201 // 箭头函数可以不带ruturn
})

// es6 简写
data.filter((item, i) => item.id != 201)

    1.2 年龄过滤

var age = [14, 22, 18, 20];

var newAge = age.filter(function(item){
  return item >= 18; // 非箭头函数必须带return
});
console.log(newAge); // [22, 18, 20]

 2 取得数组中的最大值和最小值

var values = [1, 2, 4, 6, 8, 9];
var max = Math.max.apply(Math, values);
var min = Math.min.apply(Math, values);
console.log(max);
console.log(min);

// 关键把Math作为apply()的第一个参数,使得this指向Math

 

posted @ 2017-05-02 17:50  Jesonhu  阅读(128)  评论(0编辑  收藏  举报
Top