ES6中,经常使用的数组方法

1.filter数组

filter:“过滤”、“筛选”。指数组filter后,返回新数组(经过callback函数测试的全部元素)。函数

var a1 = ['a', 10, 'b', 20, 'c', 30];
var a2 = a1.filter(function(item) {
            //callback必须返回true或者false,返回true保留该元素,false不保留。
             return typeof item === 'number';
          });
console.log(a2); // [10,20,30]

2.map
map:方法返回一个由原数组中的每一个元素调用一个指定方法后的返回值组成的新数组.
不修改调用的原数组测试

var a = [1, 2, 3, 4, 5]
var b = a.map((
        return item + 1;
    });
console.log(b);   // [2, 3, 4, 5, 6]
var b2 = a.map((item) => {
      if(item >3){
        return item;
      }
  });
console.log(b2);   // [undefined, undefined, undefined, 4, 5]

3.forEach
简单来讲,就是遍历数组元素code

var a = [1, 2, 3, 4, 5];

var b = [];
a.forEach((item) => {
    b.push(item + 1);
});
console.log(b); // [2,3,4,5,6]

4.fill
fill: 使用给定值,填充一个数组从起始索引到终止索引 内的所有元素。(不包括终止索引)
空数组的初始化比较方便索引

var a = [1, 2, 3].fill(6);
console.log(a);// [6, 6, 6]

var b = new Array(6).fill(9);
console.log(b);// [9, 9, 9, 9, 9, 9]

var b = b.fill(1, 1);
console.log(b);// [9, 1, 1, 1, 1, 1]

var b = b.fill(6, 1, 3);
console.log(b);// [9, 6, 6, 1, 1, 1]

5.every 和 some
every测试数组中全部元素是否都经过了指定函数的测试
some测试数组中是否至少有一项元素经过了指定函数的测试it

var a = [1, 2, 3, 4];
  var bb = a.every((item) => {
      return item > 2;
  });

  console.log(bb); // false
  var cc = a.some((item) => {
      return item > 2;
  });
  console.log(cc);// true
相关文章
相关标签/搜索