Javascript Slice method with Example
What is JavaScript Array slice ?
Array.prototype.slice is a JS Array method that is used to extract a contiguous subarray or "slice" from an existing array.
JavaScript slice can take two arguments: the start and the end indicator of the slice -- both of which are optional. It can also be invoked without any argument. So, it has the following call signatures:
// slice(); slice(start); slice(start, end);
If I want to slice the array to take a portion of it, there actually has a built-in function slice for Javascript. Right out of the box, it’ll clone the original array.
[1,2,3].slice() // [1,2,3]
The result points to a new memory address, not the original array. This can be really useful if you want to chain the result with other functions. The real usage is when you provide some input to the slice.
Start Index
The slice can take up to two input parameters. The first one is called the start index, and this would tell where it should start the slice.
[1,2,3].slice(0) // returns [1,2,3]; Original array unmodified [1,2,3].slice(1) // returns [2,3]; Original array unmodified [1,2,3].slice(2) // returns [3]; Original array unmodified [1,2,3].slice(3) // returns []; Original array unmodified
By default, it’ll slice till the end of the array. The interesting thing about the start index is that not only you can use a zero or a positive number, but also you can use a negative number.
[1,2,3].slice(-1) // [3] [1,2,3].slice(-2) // [2,3] [1,2,3].slice(-3) // [1,2,3]
When it’s a negative number, it refers to an index counting from the end n . For instance, -1 refers to the last element of the array, -2 refers to the second last element, and etc. Notice there’s no -0 , because there’s no element beyond the last element. This can be quite apparent or confusing depending on the situation.
End index
The slice can take a second parameter called the end index.
[1,2,3].slice(0,3) // [1,2,3] [1,2,3].slice(0,2) // [1,2] [1,2,3].slice(0,1) // [1]
The end index, also referred as a range index, points to the element index + 1. What does it mean? To explain this, it would be relatively easier if we can relate to the for statement:
for (let i = 0; i < n; i++) {}
The variable i starts at 0 , the start index; and ends at n, the end index. The end index isn’t the last element of the array, because that would be n - 1 . But when it comes to the end index, n stands for the “end” with the the last element included. If it’s your first time using the end index, just remember how for statement is written, or simply remember taking the last element index and then plus one to it. Another way to think of it is that the end index is open ended, [start, end).
As in the start index, the end index can be negative as well.
1,2,3].slice(0,-1) // [1,2] [1,2,3].slice(0,-2) // [1]
Pay a bit more attention here. -1 refers to the last element, therefore if used as the second parameter, it means the last element will be excluded, as we have explained, open ended.
Kool but what if I want to include the last element?
[1,2,3].slice(0) // [1,2,3]
Yes, simply use the single parameter input.
How to Use JavaScript slice: Real Example
A typical example of slicing an array involves producing a contiguous section from a source array. For example, the first three items, last three items and some items spanning from a certain index up until another index.
As shown in the examples below:
const elements = [ "Please", "Send", "Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked", ]; const firstThree = elements.slice(0, 3); // ["Please", "Send", "Cats"] const lastThree = elements.slice(-3, elements.length); // ["Make", "Sure", "Padlocked"] const fromThirdToFifth = elements.slice(2, 5); // ["Cats", "Monkeys", "And"]
If we don't pass any argument to JavaScript slice, we get a shallow copy of the source array with all items:
const allCopied = elements.slice(); // (12) ["Please", "Send", "Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"]
It's effectively [...elements].
JavaScript Array slice Method with No Second Argument
If we don't pass the second argument, the extracted JavaScript Array slice extends to the last element:
const fromThird = elements.slice(2); // (10) ["Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"] const lastThree = elements.slice(-3, elements.length); // (3) ["Make", "Sure", "Padlocked"] const lastThreeWithNoSecArg = elements.slice(-3); // (3) ["Make", "Sure", "Padlocked"]
JavaScript Array.prototype.slice with Negative Offsets
Notice also above that, we can pass in negative numbers as arguments. Negative values of the arguments denote offset positions counted backwards from the last item. We can do this for both arguments:
const latestTwoBeforeLast = elements.slice(-3, -1); // (2) ["Make", "Sure"]
If we pass in a greater value for start than end, we get an empty array:
const somewhereWeDontKnow = elements.slice(5, 2); // []
This indicates we have to always start slicing from a lesser positive index.
Array.prototype.slice: Starting Position Greater Than Length of Array
Likewise, if we pass in a greater value for start than array's length, we get an empty array:
const somewhereInOuterSpace = elements.slice(15, 2); // []
Using JS slice with Sparse Arrays
If our target slice has sparse items, they are also copied over:
const elements = [ "Please", "Send", , "Cats", , "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked", ]; const sparseItems = elements.slice(0, 6); // (6) [ 'Please', 'Send', <1 empty item>, 'Cats', <1 empty item>, 'Monkeys' ]
Array.prototype.slice: Creating Arrays from a List of Arguments
In this section we go a bit crazy about slicing. We develop two interesting ways with Array.prototype.slice to construct an array from a list of arguments passed to a function.
The first one:
const createArray = (...args) => Array.prototype.slice.call(args); const array = createArray(1, 2, 3, 4); // (4) [1, 2, 3, 4]
That was easy.
The next level way of doing this is in the messiest possible way:
const boundSlice = Function.prototype.call.bind(Array.prototype.slice); const createArray = (...args) => boundSlice(args); const array = createArray(1, 2, 3, 4); // (4) [1, 2, 3, 4]
Slicing a JavaScript String
const mnemonic = "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"; const firstThreeChars = mnemonic.slice(0, 3); // "Ple" const lastThreeChars = mnemonic.slice(-3, mnemonic.length); // "ked" const fromThirdToFifthChars = mnemonic.slice(2, 5); // "eas"
Again, both arguments represent zero-based index numbers or offset values. Here too, the first argument -- 0 in the firstThree assignment -- stands for the starting index or offset in the source array. And the second argument (3) denotes the index or offset before which extraction should stop.
JavaScript String Slice Nuances
Using JavaScript String slice With No Arguments
Similar to Array slice, if we don't pass any argument to String slice(), the whole string is copied over:
const mnemonic = "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"; const memorizedMnemonic = mnemonic.slice(); // "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"
JavaScript String slice with Negative Offsets
Similar to Array.prototype.slice, negative values for start and end represent offset positions from the end of the array:
const mnemonic = "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"; const lastThreeChars = mnemonic.slice(-3); // "ked" const latestTwoCharsBeforeLast = mnemonic.slice(-3, -1); // "ke"
Summary
In this post, we expounded the slice() method in JavaScript. We saw that JavaScript implements slice() in two flavors: one for Arrays with Array.prototype.slice and one for Strings with String.prototype.slice. We found out through examples that both methods produce a copy of the source object and they are used to extract a target contiguous slice from it.
We covered a couple of examples of how function composition and context binding with Function.prototype.call and Function.prototype.bind allows us to define custom functions using Array.prototype.slice to help us generate arrays from a list of arguments.
We also saw that String.prototype.slice is an identical implementation of Array.prototype.slice that removes the overhead of converting a string to an array of characters.
以上是Javascript Slice method with Example的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

实现视差滚动和元素动画效果的探讨本文将探讨如何实现类似资生堂官网(https://www.shiseido.co.jp/sb/wonderland/)中�...

学习JavaScript不难,但有挑战。1)理解基础概念如变量、数据类型、函数等。2)掌握异步编程,通过事件循环实现。3)使用DOM操作和Promise处理异步请求。4)避免常见错误,使用调试技巧。5)优化性能,遵循最佳实践。

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

如何在JavaScript中将具有相同ID的数组元素合并到一个对象中?在处理数据时,我们常常会遇到需要将具有相同ID�...

探索前端中类似VSCode的面板拖拽调整功能的实现在前端开发中,如何实现类似于VSCode...
