filter是Javascript中Array常用的操作,它用于把Array的某些元素过滤掉,然后返回剩下的元素
1 var arr = ['A', 'B', 'C'
];
2 var r = arr.filter(
function (element, index, self) {
3 console.log(element);
// 依次打印'A', 'B', 'C'
4 console.log(index);
// 依次打印0, 1, 2
5 console.log(self);
// self就是变量arr
6 return true;
7 });
利用 filter,可以巧妙地去除Array的重复元素:
var arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'
];
r = arr.filter(
function (element, index, self) {
return self.indexOf(element) ===
index;
});
console.log(r.toString());
参考:
https://www.jb51.net/article/99038.htm
转载于:https://www.cnblogs.com/wangxinbo/p/11219009.html