joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
  404 随笔 :: 39 文章 :: 8 评论 :: 20万 阅读

slice() 是 JavaScript 中用于提取数组的一部分或字符串的一部分的方法。slice() 不会修改原始数组或字符串,而是返回一个新数组或字符串。

对于数组

语法:

array.slice(begin, end)
  • begin:要提取的起始索引(包含)。如果省略,默认从索引 0 开始。
  • end:要提取的结束索引(不包含)。如果省略,默认提取到数组的末尾。

示例:

let fruits = ["apple", "banana", "orange", "mango", "pear"];

// 提取从索引 1 到索引 3(不包含)的元素
let citrus = fruits.slice(1, 3);
console.log(citrus); // ["banana", "orange"]

// 提取从索引 2 到数组末尾的元素
let tropical = fruits.slice(2);
console.log(tropical); // ["orange", "mango", "pear"]

对于字符串

语法:

string.slice(begin, end)
  • begin:要提取的起始索引(包含)。如果省略,默认从索引 0 开始。
  • end:要提取的结束索引(不包含)。如果省略,默认提取到字符串的末尾。

示例:

let message = "Hello, world!";

// 提取从索引 7 到索引 12(不包含)的字符
let world = message.slice(7, 12);
console.log(world); // "world"

// 提取从索引 0 到索引 5(不包含)的字符
let hello = message.slice(0, 5);
console.log(hello); // "Hello"

负索引

slice() 方法也支持负索引,这意味着从数组或字符串的末尾开始计算。

示例:

let numbers = [1, 2, 3, 4, 5];

// 提取从索引 -3 到数组末尾的元素
let lastThree = numbers.slice(-3);
console.log(lastThree); // [3, 4, 5]

let greeting = "Good morning!";

// 提取从索引 -8 到字符串末尾的字符
let morning = greeting.slice(-8);
console.log(morning); // "morning!"
posted on   joken1310  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示