拼接和切片的区别是什么?
const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);
拼接和切片的区别是什么?
const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);
当前回答
这里有一个简单的技巧来记住切片和拼接之间的区别
var a=['j','u','r','g','e','n'];
// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]
//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]
要记住的技巧:
将“spl”(splice的前3个字母)视为“指定长度”的缩写,即第二个参数应该是长度而不是索引
其他回答
splice()方法返回数组中已删除的项。 slice()方法将数组中所选的元素作为一个新的数组对象返回。
splice()方法改变原始数组,slice()方法不改变原始数组。
Splice() method can take n number of arguments: Argument 1: Index, Required. Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed. Argument 3..n: Optional. The new item(s) to be added to the array. slice() method can take 2 arguments: Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array. Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.
这里有一个简单的技巧来记住切片和拼接之间的区别
var a=['j','u','r','g','e','n'];
// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]
//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]
要记住的技巧:
将“spl”(splice的前3个字母)视为“指定长度”的缩写,即第二个参数应该是长度而不是索引
S LICE =给出数组的一部分&没有分裂原始数组
SP LICE =给出数组的一部分&分裂原始数组
我个人觉得这更容易记住,因为这两个术语总是让我这个网页开发初学者感到困惑。
大多数答案都太啰嗦了。
拼接和切片返回数组中其余的元素。 拼接使被操作的数组发生突变,删除元素,而切片没有。
Splice()改变原始数组,而slice()不会,但它们都返回数组对象。
请看下面的例子:
var array=[1,2,3,4,5];
console.log(array.splice(2));
这将返回[3,4,5]。原始数组受到影响,导致数组为[1,2]。
var array=[1,2,3,4,5]
console.log(array.slice(2));
这将返回[3,4,5]。原始数组不受影响,导致数组为[1,2,3,4,5]。
下面是简单的小提琴,它证实了这一点:
/ /拼接 数组var =[1、2、3、4、5); console.log (array.splice (2)); / /片 var array2 =[1、2、3、4、5) console.log (array2.slice (2)); console.log(“——后——”); console.log(数组); console.log (array2);