如何进行这种转变?
["a","b","c","d","e"] // => ["c", "d", "e"]
我以为slice
可以做到这一点,但是..
["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ]
["a","b","c","d","e"].slice(2,0) // []
如何进行这种转变?
["a","b","c","d","e"] // => ["c", "d", "e"]
我以为slice
可以做到这一点,但是..
["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ]
["a","b","c","d","e"].slice(2,0) // []
不要使用第二个参数:
Array.slice(2);
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
如果 end 被省略,切片将提取到序列的末尾。
与@insomniac 的答案有关的一个重要考虑因素是splice
和slice
是两个完全不同的功能,主要区别在于:
splice
操作原始数组。slice
返回原始数组的子集,原始数组保持不变。请参阅:http ://ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.html了解更多信息。
只需给出起始索引,因为您想要数组中的其余数据..
["a","b","c","d","e"].splice(2) => ["c", "d", "e"]
["a","b","c","d","e"].slice(-3) => ["c","d","e"]
切片在指定的结束参数处结束,但不包括它。如果要包含它,则必须将最后一个索引指定为数组的长度(在本例中为 5),而不是结束索引(-1)等。
["a","b","c","d","e"].slice(2,5)
// = ['c','d','e']
必须在 n 之前添加一个“-” 如果索引为负数,则 end 表示与 end 的偏移量。
function getTail(arr, n) {
return arr.slice(-n);
}
var arr = ["a", "b", "c", "d", "e"];
arr.splice(0,2);
console.log(arr);