今天 在代码里看见了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
代表了数组元素的索引