js方法 Array.prototype.slice()

今天 在代码里看见了fileList.slice(-1) 不明白它的意思 于是打算系统学一下slice()方法

参看文献   https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

slice返回一个新的数组 新数组是浅拷贝 所以不改变原数组 返回的新数组又start和end决定(包含start不包含end)

语法

slice()
slice(start)
slice(start, end)

1.slice()返回原数组

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

2.slice(start)返回第start到最后一个元素

特殊情况:

start不为整数:向下取整 

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2.1));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(1.9));
// Expected output: Array  ["bison", "camel", "duck", "elephant"]

start为负数start >-array.length将其转换为start + array.length

                      start < -array.length 或者省略了 start,则使用 0

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(-9));
// Expected output: ["ant", "bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
 

如果 start >= array.length,则不提取任何元素。

3.slice(start,end)

s这一对是一个由 start 和 end 决定的原数组的浅拷贝(包括 start,不包括 end),其中 start 和 end 代表了数组元素的索引

相关推荐

  1. js字符串的方法

    2024-05-12 13:40:04       44 阅读
  2. js数组方法笔记

    2024-05-12 13:40:04       38 阅读
  3. js- find() 方法

    2024-05-12 13:40:04       19 阅读
  4. js sort() 方法

    2024-05-12 13:40:04       12 阅读
  5. js 七种继承方法

    2024-05-12 13:40:04       35 阅读
  6. js join方法的使用

    2024-05-12 13:40:04       43 阅读
  7. js some方法的使用

    2024-05-12 13:40:04       36 阅读
  8. js indexOf方法的使用

    2024-05-12 13:40:04       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-12 13:40:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-12 13:40:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-12 13:40:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-12 13:40:04       20 阅读

热门阅读

  1. 中文域名有必要注册吗?

    2024-05-12 13:40:04       10 阅读
  2. 如何自定义双亲委派中类的加载器

    2024-05-12 13:40:04       10 阅读
  3. Elasticsearch安装

    2024-05-12 13:40:04       11 阅读
  4. react 屏幕信息滚动

    2024-05-12 13:40:04       11 阅读
  5. 安全架构设计理论与实践

    2024-05-12 13:40:04       12 阅读
  6. 【WPF】聊聊WPF中INotifyPropertyChanged [TOC]

    2024-05-12 13:40:04       10 阅读
  7. 使用poi生成word文件时,zip相关的报错

    2024-05-12 13:40:04       10 阅读