This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
There are a lot of array methods, in the process of the interview also encountered a lot of. It’s not just the use of array methods. If you really want to understand and master array methods, you can also implement them to deepen your memory.
Class array to array
What is a class array?
- A class array is an array-like object that has the length property of an array but does not have the methods of an array prototype.
Common class array are: the arguments, DOM manipulation returned results (such as the document. The getElementsByTagName ())
So a lot of times, we need to convert an array of classes to an array, so that we can use the methods on the array prototype.
How do I convert an array of classes to an array?
Here are a few ways to convert:
1, the Array. The from
let newArr1 = Array.from(classArr);
Copy the code
2, Array. Prototype. Slice. The call ()
let newArr2 = Array.prototype.slice.call(classArr);
Copy the code
3. Extend operators
let newArr3 = [...classArr];
Copy the code
4. Concatenate arrays using concat
let newArr4 = Array.prototype.concat.apply([], classArr)
Copy the code
These four methods are the most common and useful conversion methods.
Ii. Handwritten filter()
The use of the filter ()
A filter is used to filter out the elements in an array that match the criteria. Note: Filter does not alter the original array
1. For example, we can use filter to filter out all even numbers in an array
let arr = [56.15.48.3.7];
let newArr = arr.filter(function(value, index, array) {
return value % 2= = =0;
});
console.log(newArr); / / [56] 13
Copy the code
2. Alternatively, filter can be used to implement array de-duplication
function unique(arr) {
return arr.filter(function(item, index, arr) {
// Current element, the first index in the original array == current index value, otherwise return current element
return arr.indexOf(item, 0) === index;
});
}
Copy the code
To realize the filter ()
First look at the syntax of filter:
array.filter(function(currentValue,index,arr), thisValue)
Copy the code
Parameters:
currentValue
: Mandatory, the value of the current elementindex
: Optional, index value of the current elementarr
: Optional array object to which the current element belongsthisValue
: Optional, the object is used when the callback is executed, passed to the function, as the value of this
Here is the concrete implementation method:
Array.prototype.filter = function(callback, thisArg) {
if (this= =undefined) {
throw new TypeError('this is null or not undefined');
}
if (typeofcallback ! = ='function') {
throw new TypeError(callback + 'is not a function');
}
const res = [];
// make O an object pass for the callback function (cast object)
const O = Object(this);
// >>>0 Ensure that len is number and a positive integer
const len = O.length >>> 0;
for (let i = 0; i < len; i++) {
// Check if I is an attribute of O (prototype chain is checked)
if (i in O) {
// The callback function call passes arguments
if(callback.call(thisArg, O[i], i, O)) { res.push(O[i]); }}}return res;
}
Copy the code
ForEach ()
The use of the forEach ()
The forEach() method is used to call each element of the array and pass the element to the callback function. This statement takes a callback function as an argument. Note: forEach returns undefined.
For example, forEach() iterates through the array and prints the value of the element:
var arr = ['a'.'b'.'c'];
arr.forEach(function(value, index, arr) {
console.log(value); // a b c
})
Copy the code
Implement the forEach ()
ForEach () syntax
array.forEach(function(currentValue, index, arr), thisValue)
Copy the code
currentValue
: Mandatory, the value of the current elementindex
: Optional, index value of the current elementarr
: Optional array object to which the current element belongsthisValue
: Optional, the value passed to the function is usually “this”. If this parameter is empty, “undefined” is passed to the value “this”
Here is the concrete implementation method:
Array.prototype.forEach = function(callback, thisArg) {
if (this= =null) {
throw new TypeError("this is null or not defined");
}
if (typeofcallback ! = ='function') {
throw new TypeError(callback + "is not a function")}const O = Object(this);
const len = O.length >>> 0;
let k = 0;
while (k < len) {
if (k inO) { callback.call(thisArg, O[k], k, O); } k++; }}Copy the code
Iv. Handwritten map()
The use of the map ()
The map() method also does a series of operations on arrays. And returns a new array with the values of the original array elements. Note: Map () does not change the original array.
1. For example, we want to return an array whose elements are the square root of the original array. It can be implemented like this:
var nums = [4.9.16.25];
function fn(nums) {
return nums.map(Math.sqrt)
}
console.log(fn(nums)); // [2, 3, 4, 5]
Copy the code
2. Alternatively, multiply each element of the array by the value specified in the input box and return the new array
var nums = [4.9.16.25];
function fn2() {
return nums.map(function(item, index, arr) {
// return num * document.getElementById("multiplyWith").value;
return item * 2})}console.log(fn2(nums)); // [8, 18, 32, 50]
Copy the code
To realize the map ()
Let’s start with the syntax for map() :
array.map(function(currentValue,index,arr), thisValue)
Copy the code
currentValue
: Mandatory, the value of the current elementindex
: Optional, index value of the current elementarr
: Optional array object to which the current element belongsthisValue
: Optional, the object is used when the callback is executed, passed to the function, as the value of this
Here is the concrete implementation method:
Array.prototype.map = function(callback, thisArg) {
if (this= = =undefined) {
throw new TypeError("this is null or not defined");
}
if (typeofcallback ! = ='function') {
throw new TypeError(callback + 'is not a function')}const res = [];
// make O an object pass for the callback function (cast object)
const O = Object(this);
// >>>0 Ensure that len is number and a positive integer
const len = O.length >>> 0;
for (let i = 0; i < len; i++) {
// Check if I is an attribute of O (prototype chain is checked)
if (i in O) {
// Call the callback function and pass in a new array
res[i] = callback.call(thisArg, O[i], i, this)}}return res;
}
Copy the code
V. Handwriting reduce()
The use of the reduce ()
The reduce() method is used to evaluate array elements as a value (left to right). This method takes a function as an accumulator and computes it to the final value.
For example, calculating the sum of the rounded elements of an array:
var nums = [1.2.3]
function getSum(total, num) {
return total + Math.round(num)
}
function fn(item) {
return nums.reduce(getSum, 0)}console.log(fn(nums)); / / 6
Copy the code
To realize the reduce ()
Let’s look at the syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code
currentValue
: Mandatory, the value of the current elementindex
: Optional, index value of the current elementarr
: Optional array object to which the current element belongsthisValue
: Optional, the value passed to the function is usually “this”. If this parameter is empty, “undefined” is passed to the value “this”
Here is the concrete implementation method:
Array.prototype.reduce = functon((callback, initialValue) {
if (this= = =undefined) {
throw new TypeError('this is null or not defined')}if (typeofcallback ! = ='function') {
throw new TypeError(callback + 'is not a function')}const O = Object(this);
const len = O.length >>> 0;
let accumulator = initialValue; / / accumulator
let k = 0;
// If the second parameter is undefined
// The first valid value of the array is the initial value of the accumulator
if (accumulator === undefined) {
while(k < len && ! (kin O)) {
k++;
}
// If the array bounds are exceeded and the initial value of the accumulator is not found, an error is thrown
if (k >= len) {
throw new TypeError("Reduce of empty array with no initial value")
}
accumulator = O[k++]
}
while (k < len) {
if (k in O) {
accumulator = callback.call(undefined, accumulator, O[k], k, O)
}
k++;
}
return accumulator;
})
Copy the code
conclusion
This is probably the way arrays are commonly used, whether in interviews, or in actual development, array methods are common, more thinking and more practice helps to deepen memory.