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

Javascript Slice method with Example

Sep 20, 2024 am 06:54 AM

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

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

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1653
14
CakePHP 教程
1413
52
Laravel 教程
1304
25
PHP教程
1251
29
C# 教程
1224
24
前端热敏纸小票打印遇到乱码问题怎么办? 前端热敏纸小票打印遇到乱码问题怎么办? Apr 04, 2025 pm 02:42 PM

前端热敏纸小票打印的常见问题与解决方案在前端开发中,小票打印是一个常见的需求。然而,很多开发者在实...

神秘的JavaScript:它的作用以及为什么重要 神秘的JavaScript:它的作用以及为什么重要 Apr 09, 2025 am 12:07 AM

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

谁得到更多的Python或JavaScript? 谁得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

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

如何实现视差滚动和元素动画效果,像资生堂官网那样?
或者:
怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? 如何实现视差滚动和元素动画效果,像资生堂官网那样? 或者: 怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? Apr 04, 2025 pm 05:36 PM

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

JavaScript难以学习吗? JavaScript难以学习吗? Apr 03, 2025 am 12:20 AM

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

JavaScript的演变:当前的趋势和未来前景 JavaScript的演变:当前的趋势和未来前景 Apr 10, 2025 am 09:33 AM

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

如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? 如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? Apr 04, 2025 pm 05:09 PM

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

前端开发中如何实现类似 VSCode 的面板拖拽调整功能? 前端开发中如何实现类似 VSCode 的面板拖拽调整功能? Apr 04, 2025 pm 02:06 PM

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

See all articles