This is the 29th day of my participation in the genwen Challenge
This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.
If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.
Note that it is a simple implementation, not a complete implementation, it is important to clear the concept and clear implementation ideas, it is suggested to explain the concept first => write use cases => write pseudo-code => then realize specific functions, and then optimize, step by step.
21. Array.prototype.map()
What is the
The map() method creates a new array with the result that each element in the array is the return value from a call to the provided function.
The test case
let arr = [1.2.3]
let test1 = arr.map(item= > item * 2)
let test2 = arr.map((it, index) = > {
return {
idx: index,
value: it
}
})
console.log(test1)
// [2, 4, 6]
console.log(test2)
// [ { idx: 0, value: 1 }, { idx: 1, value: 2 }, { idx: 2, value: 3 } ]
console.log(arr)
// [1, 2, 3] the original array remains unchanged
Copy the code
grammar
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
Copy the code
parameter
callback
- A function that generates a new array element, taking three arguments:
currentValue
: The current element being processed in the callback array.index
Optional: Index of the current element being processed in the callback array.array
Optional: Array of map method calls.
- A function that generates a new array element, taking three arguments:
thisArg
optional- The value is used as this when the callback function is executed.
Return value A new array consisting of the result of each element of the original array executing the callback function.
describe
-
The map method calls the callback function once, in order, for each element in the array. The return values (including undefined) from each callback are combined to form a new array. Callback is called only on indexes that have values; Indexes that have never been assigned a value or deleted with delete are not called.
-
Since a map generates a new array, using a map when you don’t intend to use the returned array is against the design. Use forEach or for-of instead. There are two situations where you should not use map:
- You are not going to use the new array returned
- You did not return a value from the callback function.
-
The callback function is automatically passed three parameters: the array element, the element index, and the original array itself.
-
If thisArg is supplied to map, it will be used as the this value of the callback. Otherwise, undefined will be used as this for the callback function.
-
The map does not modify the array that calls it (although it can change the array when the callback executes).
-
The scope of the map method’s handling of array elements is determined before the callback method is first called. The array elements appended after the map method is called are not accessed by the callback. If an existing array element changes, the value passed to the callback is the value at which the map accessed the element. The element cannot be accessed if it is deleted after the map function is called but before it is accessed.
-
According to the algorithm defined in the specification, if the array called by map is discrete, the new array will also be discrete, leaving the same index empty.
Simple handwriting implementation
Let’s summarize the key points before implementation:
-
The map method basically calls the callback function once for each element in the array, in order. And combine all the returned results together to generate a new array return.
-
Two arguments, mandatory callback and optional thisArg (this value when callbackfn is executed)
Just use the test case above
Array.prototype.myMap = function(callbackfn, thisArg) {
// The array returns null, and the array returns null
if (this= =null) {
throw new TypeError("Cannot read property 'map' of null or undefined");
}
// Callbackfn throws an exception when it is not a function
if (typeofcallbackfn ! = ='function') {
throw new TypeError(callbackfn + ' is not a function')}// This becomes an array object with iterators
let O = Object(this)
// Create a new array without affecting the original array
let newArr = new Array(O.length)
for (let k = 0; k < O.length; k++) {
// Check whether O and its prototype chain contain the attribute k
if (k in O) {
let currentValue = O[k]
ThisArg, currentValue, index(k), array(O)
let mappedValue = callbackfn.call(thisArg, currentValue, k, O)
// Assign the result to the new array
newArr[k] = mappedValue
}
}
return newArr
}
let arr = [1.2.3]
let test1 = arr.myMap(item= > item * 2)
let test2 = arr.myMap((it, index) = > {
return {
idx: index,
value: it
}
})
console.log(test1)
// [2, 4, 6]
console.log(test2)
// [ { idx: 0, value: 1 }, { idx: 1, value: 2 }, { idx: 2, value: 3 } ]
console.log(arr)
// [1, 2, 3]
Copy the code
22. Array.prototype.filter()
What is the
The filter() method creates a new array containing all the elements of the test implemented through the provided function. The main function is actually filtering.
// let arr = [1, 2, 3, 4, 5, 6]
// let test1 = arr.filter(item => item > 3)
// console.log(test1)
// // [4, 5, 6]
// console.log(arr)
// // [1, 2, 3, 4, 5, 6]
Copy the code
grammar
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
Copy the code
parameter
callback
- A function that tests each element of an array. return
true
Indicates that the element passes the test, the element is retained,false
Is not reserved. It takes the following three parameters:element
: The element in the array currently being processed.index
Optional: Index of the element being processed in the array.array
Optional: The array itself of filter is called.
- A function that tests each element of an array. return
thisArg
optional- The value used for this when callback is executed.
Returns a new array of elements that have passed the test, or an empty array if none of the elements have passed the test.
describe
-
Filter calls callback once for each element in the array and creates a new array with all elements that cause callback to return true or its equivalent.
-
Callback will only be called on indexes that have been assigned, not indexes that have been deleted or never assigned. Elements that do not pass the callback test are skipped and not included in the new array.
-
Callback is called with three arguments:
- The value of the element
- Index of an element
- The array itself being iterated over
-
If a thisArg argument is provided to filter, it will be used as this when callback is called.
-
Filter does not alter the original array; it returns the filtered new array.
-
The range of elements traversed by filter is determined before the first callback is called. Elements added to the array after a call to filter are not traversed by filter. If existing elements are changed, the value they pass to the callback is the value filter traverses up to that point in time. Elements that are deleted or never assigned are not traversed.
Simple handwriting implementation
Summarize the key points before implementation:
-
The filter method is used to filter the elements of an array. It needs to set a test function called callback. Leave all test functions that return true or their equivalent.
-
ThisArg (this value when callback is executed); thisArg (thisValue when callback is executed);
Implementation is not difficult, and map is similar, look at the code
Array.prototype.myFilter = function(callback, thisArg) {
// The instructions above are omitted here
if (this= =null) {
throw new TypeError("Cannot read property 'filter' of null or undefined");
}
if (typeofcallback ! = ='function') {
throw new TypeError(callback + ' is not a function')}let O = Object(this)
let newArr = new Array(O.length)
let to = 0
for (let k = 0; k < O.length; k++) {
if (k in O) {
let element = O[k]
// Callback is a judgment function
if (callback.call(thisArg, element, k, O)) {
newArr[to++] = element;
}
}
}
newArr.length = to;
return newArr
}
let arr = [1.2.3.4.5.6]
let test1 = arr.myFilter(item= > item > 3)
console.log(test1)
// [4, 5, 6]
console.log(arr)
// [1, 2, 3, 4, 5, 6]
Copy the code
In addition, we recommend another series of articles, very simple, on the front of the advanced students are very effective, wall crack recommended!! Core concepts and algorithms disassembly series remember to like ha
If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions
reference
- Developer.mozilla.org/zh-CN/docs/…
- Developer.mozilla.org/zh-CN/docs/…