Fork me on Gitee

数组处理方法——filter

数组处理方法——filter()

一、作用

filter用于对数组进行过滤。它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

二、语法

Array.filter(function(currentValue, indedx, arr), thisValue)

其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;函数的第一个参数 currentValue 也为必须,代表当前元素的值。

三、示例

image-20221116092101090

四、注意

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

filter() 不会改变原始数组。但是对filter()得到的新数组,新数组里引用数据类型的改变,原数组也会相应改变,因为新数组里引用数据类型的数据项的指针仍然指向的是原数组的数据项。对于修改基本数据类型的数据是不会改变原数组的。

示例:

    testFilter() {
      var tempList = [
        {
          name: 'haha',
          sex: '女'
        },
        {
          name: 'xinling',
          sex: '女'
        },
        {
          name: 'xiang',
          sex: '男'
        }
      ]
      var newT = tempList.filter((item) => {
        return item.sex == '女'
      })
      console.log('-----newT===', newT)
      newT.forEach(it => {
        if(it.name == 'xinling') {
          // it.type = '明星'
          it['type'] = '明星'
          it.sex = ' beautiful girl'
        }
      })
      console.log('-----newT2===', newT)

      console.log('-----tempList===', tempList)
    }

image-20221116101723865

可以看出对filter出来的newT,修改newT里面的数据后,tempList里的数据也变化了。

posted @ 2022-11-16 10:34  等风的羽毛  阅读(1524)  评论(0编辑  收藏  举报
1