fliter()函数

796 阅读1分钟

fliter()函数 --过滤

  1. 返回通过测试的元素,无则返回一个空数组。
  2. 不会改变调用的数组,但会将满足条件生成新的数组。
  3. 该数组强制返回为true的值

filter(element,index,array)

  • element

  • 数组中正在处理的当前元素,元素的值

  • index

  • 数组中正在处理的当前元素的索引

  • array

  • 在其上调用的数组。

例子:返回数组中的所有质数

const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i === 0) {  //在满足num>i的情况下,每个数与num-1相余有等于0false,无责return num>1,比如9循环了2次到余为0
      return false;
    }
  }
  return num > 1;
}

console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]

例子:当想要影响初始数据的值时

修改数据

// 修改数据
let words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present'];

const modifiedWords = words.filter((word, index, arr) => {
  arr[index + 1] += ' extra';//将从arr[1]开始在内容后面添加extra,一直加到最后
  return word.length < 6;//长度小于6个有3个值 
});

console.log(modifiedWords);
->["spray"]
//因为其他两个被修改了,所以只返回了spray

添加数据

// 添加
words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present'];
const appendedWords = words.filter((word, index, arr) => {
  arr.push('new');
  return word.length < 6;
})

console.log(appendedWords); 
->["spray" ,"limit" ,"elite"]
//只有三个符合条件,即使“words”本身现在有更多字符长度小于6的单词

删除数据

// 删除
words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present'];
const deleteWords = words.filter((word, index, arr) => {
  arr.pop();
  
  return word.length < 6;
})

console.log(deleteWords);
-> ["spray" ,"limit"]
//虽然"elite"也符合条件,但是在它之后的两个不满足条件也还是会继续删,
//如果 'exuberant', 'destruction'的长度小于6,那么就会整串从'spray'到'elite'都能输入