拼接和切片的区别是什么?
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);
当前回答
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);
大多数答案都太啰嗦了。
拼接和切片返回数组中其余的元素。 拼接使被操作的数组发生突变,删除元素,而切片没有。
Slice()和Splice() javascript内置函数之间的区别是, Slice返回删除的项,但没有改变原始数组; 就像,
// (original Array)
let array=[1,2,3,4,5]
let index= array.indexOf(4)
// index=3
let result=array.slice(index)
// result=4
// after slicing=> array =[1,2,3,4,5] (same as original array)
但在splice()情况下,它会影响原始数组;就像,
// (original Array)
let array=[1,2,3,4,5]
let index= array.indexOf(4)
// index=3
let result=array.splice(index)
// result=[4,5]
// after splicing array =[1,2,3] (splicing affects original array)
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.
切片和拼接紧密相连,但用途却截然不同:
slice函数用于选择数组的一部分。它的目的是返回值。它的执行并不影响它的主题。
splice函数用于从数组中删除元素。它的目的是修饰它的主题。如果需要,它仍然返回已删除项的副本,以供参考。