Translator: Front-end wisdom
Original text: codeburst. IO/js – by – examp…
The more you know, the more you don’t know
Like it and see. Make it a habit
GitHub: github.com/qq449245884… Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.
In order to ensure readability, this paper adopts free translation rather than literal translation.
The JS array slice method is one of the most powerful and commonly used built-in functions in the JS language.
With the rise of React and other feature-oriented JavaScript practices, it has become increasingly important for two reasons:
-
Functional programming, especially higher-order functions, works hand-in-hand with data lists
-
Functional programming requires pure functions, that is, functions that do not cause side effects or modify input data
The JavaScript array slice method meets both criteria.
The Slice method creates a shallow copy of a subset of the list without modifying the original list. As such, it provides a key building block for writing functional JS.
In this article, we’ll take the Slice method by example and explore its eight different uses.
Note: The slice method is not to be confused with the splice method, which modifies the original array.
How Slice works
Before diving into some more advanced uses, let’s look at the basics of the Slice method.
As in an MDN document, slice is a method on an array that takes at most two arguments:
arr.slice([begin[, end]])
Copy the code
begin
The index is used to extract elements from the original array. If this parameter is negative, it is used to extract the penultimate element from the original array. Slice (-2) is used to extract the penultimate element from the original array to the last element (including the last element). If begin is omitted, slice starts at index 0.
end
The extraction of the original array elements (starting at 0) ends at the index. Slice extracts all elements indexed from begin to end (including begin, but not end).
Slice (1,4) extracts all elements (elements indexed 1, 2, 3) from the second element in the original array up to the fourth element.
If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. Slice (-2,-1) extracts the penultimate element of the array to the last element (excluding the last element, i.e. only the penultimate element).
If end is omitted, slice extracts all the way to the end of the original array. If end is greater than the array length, Slice will also extract to the end of the array.
Basic usage
Our first four examples highlight the core features of Slice.
Usage 1: Simple copy
const arr2 = arr.slice()
Copy the code
Slice with no arguments performs a simple shallow copy. Currently, the dominant usage is still using an expansion match, but if you are in an older code base or are not using Babel’s build steps, you may still want to use slice.
Usage 2: Get the subarray starting with N
The simplest way to use slice is to extract all elements of the original array starting with N.
One case is that you want to pop up the first element of the array and use it, returning the rest of the array, but you want to do this without modifying the original array.
function useone (arr) {
const usedItem = arr[0]
return arr.slice(1)
}
Copy the code
Usage 3: Get the subarray starting at the end of N
Another way to use slice is to get the end of the array, using a negative index to count from the end.
This negative index makes it super easy to delete any number of elements. For example, if you just want to grab three
const last3 = arr.slice(-3)
Copy the code
Usage 4: Get the first n bytes of an array
To get the first number of the array, we need to use the second argument: end.
When there are two arguments, the slice method returns a collection starting with begin but excluding end.
Since JavaScript arrays start at 0 (the index starts at 0), this makes it very easy to get the first N elements:
const first4 = arr.slice(0, 4)
Usage 5: Get a subarray of an array
What if we want to use Slice to get a segment of an array starting from any index?
To do this, we need to convert from (begin, length) to (begin, end). The calculation logic is simple, and we can define a simple function to do this:
function pullSegment(arr, begin, length) {
return arr.slice(begin, begin + length);
}
Copy the code
Handles array-like objects
In JavaScript, an Array is a special object whose property name is a positive integer, whose length property changes as the Array members increase or decrease, and whose Array constructor inherits methods for manipulating arrays.
An ordinary object whose property names are all positive integers and have the corresponding Length attribute behaves like an Array even though the object is not created by the Array constructor. In this case, these objects are called “array-like objects.”
The slice method can also be used for array-like objects.
Array packages like Arguments (keys for accessing all arguments passed to a function), NodeLists (returned from any DOM API method that returns a list of nodes), and even primitive objects that use numeric indexes and add length attributes.
To use the slice method on an array-like object, you need to reference it directly from array. prototype, as shown below:
Array.prototype.slice.call(arguments)
Copy the code
It would be very useful in this particular situation.
Usage 6: Convert an array-like object to an array
A common use of slice on array-like objects is to convert them into actual arrays. Such as:
const args = Array.prototype.slice.call(arguments);
Why are you doing this? In order to use the array method. For example, imagine a function that looks like this
function addOne() {
return arguments.map(i => i+1);
}
Copy the code
This seems to work, but if you try, you’ll get errors:
> addOne(1, 2, 3)
TypeError: arguments.map is not a function
at test (repl:2:18)
at repl:1:1
at ContextifyScript.Script.runInThisContext (vm.js:44:33)
at REPLServer.defaultEval (repl.js:239:29)
at bound (domain.js:301:14)
at REPLServer.runBound [as eval] (domain.js:314:12)
at REPLServer.onLine (repl.js:440:10)
at emitOne (events.js:120:20)
at REPLServer.emit (events.js:210:7)
at REPLServer.Interface._onLine (readline.js:279:10)
Copy the code
This is because Arguments are not actually arrays, but array-like objects. You can do this using Slice, as follows:
function addOne() {
return Array.prototype.slice.call(arguments).map(i => i+1)
}
Copy the code
You can now get the data you want:
> addOne(1, 2, 3)
[ 2, 3, 4 ]
Copy the code
Usage 7: Cast superfluous arguments of arbitrary length into arrays
Sometimes you want to take the extra arguments of a function and form an array.
Newer versions of JavaScript introduce so-called Rest syntax to deal with this problem, but for compatibility with older browsers, you can use slice to do this:
function myFunc(a, b) {
const extraArgs = Array.prototype.slice.call(arguments, 2);
}
Copy the code
This allows myFunc to be called with any number of arguments, such as:
myFunc(1, 2, 3, 4, 5, 6, 7, 8)
Copy the code
ExtraArgs === [3,4,5,6,7,8]
Usage 8: Modify a specific index in an array
A powerful and common use of slice in a functional context is to replace the value of a particular item in an array.
In essence, this is simple, just assigning new values, but in the functional world, you can’t modify the original array.
Instead, slice can be used with the extension operator to return a new array that is the same but for the index to be updated:
function replaceIdx(arr, index, newVal) {
return [
...arr.slice(0, index),
newVal,
...arr.slice(index + 1)
]
}
Copy the code
Partial function application
Partial application, partial application, partial application
Another common pattern in functional programming is so-called partial function application: apply a function to a function in advance, and then return a new function.
This pattern allows you to combine functions to create greater reusability by using the same core functions with different pre-applied parameters.
While purely functional languages like Haskell themselves support partial function applications, in JavaScript we can implement a function using Slice to implement it
var partial = function() { const fn = arguments[0]; const args = Array.prototype.slice.call(arguments, 1); // Return a function that calls fn return function() { var remainingArgs = Array.prototype.slice.call(arguments); return fn.apply(this, args.concat(remainingArgs)); }}Copy the code
Communication (welcome to join the group, the group will give red envelopes on weekdays, interactive discussion of technology)
I am Xiaozhi, the author of the public account “Big Move the world”, and a lover of front-end technology. I will often share what I have learned to see, in the way of progress, mutual encouragement!
Pay attention to the public number, background welfare, you can see the welfare, you know.