// filter
/**
filter 为数组中的每个元素调用一次 callback 函数,并利用所有使得 callback 返回 true 或 等价于 true 的值 的元素创建一个新数组。callback 只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 callback 测试的元素会被跳过,不会被包含在新数组中。
filter 不会改变原数组,它返回过滤后的新数组。
filter 遍历的元素范围在第一次调用 callback 之前就已经确定了。在调用 filter
之后被添加到数组中的元素不会被 filter 遍历到。如果已经存在的元素被改变了,
则他们传入 callback 的值是 filter 遍历到它们那一刻的值。
被删除或从来未被赋值的元素不会被遍历到。
*/
/**
* 1,创建一个新的数组
* 2,去掉数组中不符合条件的元素 (去掉空元素 无效元素)
* 3,去掉数组中重复的元素
* method:
*
* var new_array = arr.filter(callback(element[, index[, array]])[, thisArg])
* new_array 一个新的通过测试的元素的集合的数组,如果没有通过测试则返回空数组
* callback 被调用时传入三个参数:
element 元素的值
index 元素的索引
array 被遍历的数组
thisArg 参数
1,未转入 thisArg 参数 或转入的是 null undefine 时,默认的是为 全局对象 (根据通常函数所看到的 "this"的规则确定的)
2,转入该参数时,在 callback 函数体中的 this 即指向该 thisArg (callback 的上下文 是 thisArg)
3,当 callback 使用了箭头函数时,thisArg 会被忽略,因为箭头函数的词法上是自动绑定了this值
*/
let test = {
number:100
}
var arr = [1, 2, 2,3,4,3];
var arr2 = arr.filter(function(x, index,self){
console.log(this.number) //输出 6次 100
return self.indexOf(x)===index
},test);
// //数组去重
// var arr = [1, 2, 2,3,4,3];
// var arr2 = arr.filter((x, index,self)=> self.indexOf(x)===index);
// console.log("------------------")
// console.log(arr2); //[ 1, 2, 3, 4 ]
// //去掉数组中 空字符串、undefined、null
// var arr = ['1','2',null, '3',null,"1",undefined,''];
// var newArr = arr.filter(item => item)
// console.log(newArr)//[ '1', '2', '3', '1' ]