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中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

将矩阵电影特效带入你的网页!这是一个基于著名电影《黑客帝国》的酷炫jQuery插件。该插件模拟了电影中经典的绿色字符特效,只需选择一张图片,插件就会将其转换为充满数字字符的矩阵风格画面。快来试试吧,非常有趣! 工作原理 插件将图片加载到画布上,读取像素和颜色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地读取图片的矩形区域,并利用jQuery计算每个区域的平均颜色。然后,使用

本文将引导您使用jQuery库创建一个简单的图片轮播。我们将使用bxSlider库,它基于jQuery构建,并提供许多配置选项来设置轮播。 如今,图片轮播已成为网站必备功能——一图胜千言! 决定使用图片轮播后,下一个问题是如何创建它。首先,您需要收集高质量、高分辨率的图片。 接下来,您需要使用HTML和一些JavaScript代码来创建图片轮播。网络上有很多库可以帮助您以不同的方式创建轮播。我们将使用开源的bxSlider库。 bxSlider库支持响应式设计,因此使用此库构建的轮播可以适应任何

核心要点 利用 JavaScript 增强结构化标记可以显着提升网页内容的可访问性和可维护性,同时减小文件大小。 JavaScript 可有效地用于为 HTML 元素动态添加功能,例如使用 cite 属性自动在块引用中插入引用链接。 将 JavaScript 与结构化标记集成,可以创建动态用户界面,例如无需页面刷新的选项卡面板。 确保 JavaScript 增强功能不会妨碍网页的基本功能至关重要;即使禁用 JavaScript,页面也应保持功能正常。 可以使用高级 JavaScript 技术(

数据集对于构建API模型和各种业务流程至关重要。这就是为什么导入和导出CSV是经常需要的功能。在本教程中,您将学习如何在Angular中下载和导入CSV文件


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器