Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
preface
Found that JS loop has a lot of, if let say, feel some will not remember, this time to comb through the JS loop statement.
Related articles in this series:
- For loop and while loop
- For in and forEach loops
- Loop Series map loop
This is the fourth article in this series on filter and some loops
filter
The filter parameter is the same as forEach. The first parameter is the callback function, and the second parameter is this. The callback function also takes value, index, and array.
Filter is used to filter unqualified “elements” that are left behind if the callback returns true
let arr = [1.2.3.4.5.6.7.8.9.10];
let res = arr.filter(function(val,index,array){
return val%2= =0;
})
console.log(res)/ /,4,6,8,10 [2]
Copy the code
Let’s implement _filter manually:
Array.prototype._filter = function (fn, thisTo) {
let newArr = [];
let key = 0;
for (let i = 0; i < this.length; i++) {
if (fn.call(thisTo, this[i], i, this)) {
newArr[key] = this[i];
key++
}
}
return newArr;
}
let arr = [1.2.3.4.5.6.7.8.9.10];
let res = arr._filter(function (val, index, array) {
return val % 2= =0;
})
console.log(res)
Copy the code
To achieve success
some
Some takes the same argument as forEach. The first argument is a callback function, and the second argument is this. The callback function takes value, index, and array.
Some is used to indicate a search, and returns true as long as an element in the array matches the criteria, false otherwise
let arr = [1.2.3.4."a"];
let res = arr.some(function(val,index,array){
return val === "a";
});
console.log(res);//true
Copy the code
Manual encapsulation is also simpler
Array.prototype._some = function (fn, thisTo) {
let res = false;
for (let i = 0; i < this.length; i++) {
if (fn.call(thisTo, this[i], i, this)) {
res = true;
break; }}return res;
}
//test code
let arr = [1.2.3.4."b"];
let res = arr._some(function (val, index, array) {
return val === "a";
});
console.log(res); //false
Copy the code
To achieve success
The end of the
That’s all about filter and some loops