搜索
首页web前端js教程Javascript Slice method with Example

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

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在JavaScript中替换字符串字符在JavaScript中替换字符串字符Mar 11, 2025 am 12:07 AM

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

jQuery检查日期是否有效jQuery检查日期是否有效Mar 01, 2025 am 08:51 AM

简单JavaScript函数用于检查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //测试 var

jQuery获取元素填充/保证金jQuery获取元素填充/保证金Mar 01, 2025 am 08:53 AM

本文探讨如何使用 jQuery 获取和设置 DOM 元素的内边距和外边距值,特别是元素外边距和内边距的具体位置。虽然可以使用 CSS 设置元素的内边距和外边距,但获取准确的值可能会比较棘手。 // 设置 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能会认为这段代码很

10个jQuery手风琴选项卡10个jQuery手风琴选项卡Mar 01, 2025 am 01:34 AM

本文探讨了十个特殊的jQuery选项卡和手风琴。 选项卡和手风琴之间的关键区别在于其内容面板的显示和隐藏方式。让我们深入研究这十个示例。 相关文章:10个jQuery选项卡插件

10值得检查jQuery插件10值得检查jQuery插件Mar 01, 2025 am 01:29 AM

发现十个杰出的jQuery插件,以提升您的网站的活力和视觉吸引力!这个精选的收藏品提供了不同的功能,从图像动画到交互式画廊。让我们探索这些强大的工具: 相关文章: 1

HTTP与节点和HTTP-Console调试HTTP与节点和HTTP-Console调试Mar 01, 2025 am 01:37 AM

HTTP-Console是一个节点模块,可为您提供用于执行HTTP命令的命令行接口。不管您是否针对Web服务器,Web Serv

自定义Google搜索API设置教程自定义Google搜索API设置教程Mar 04, 2025 am 01:06 AM

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

jQuery添加卷轴到DivjQuery添加卷轴到DivMar 01, 2025 am 01:30 AM

当div内容超出容器元素区域时,以下jQuery代码片段可用于添加滚动条。 (无演示,请直接复制到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

DVWA

DVWA

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

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。