JavaScript 数组拼接与切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37601282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:30:43  来源:igfitidea点击:

JavaScript Array splice vs slice

javascript

提问by Renat Gatin

What is the difference between spliceand slice?

splice和 和有slice什么区别?

$scope.participantForms.splice(index, 1);
$scope.participantForms.slice(index, 1);

回答by Thalaivar

splice()changes the original array whereas slice()doesn't but both of them returns array object.

splice()更改原始数组,而slice()不会更改,但它们都返回数组对象。

See the examples below:

请参阅以下示例:

var array=[1,2,3,4,5];
console.log(array.splice(2));

This will return [3,4,5]. The original array is affectedresulting in arraybeing [1,2].

这将返回[3,4,5]。的原始阵列受到影响,导致array[1,2]

var array=[1,2,3,4,5]
console.log(array.slice(2));

This will return [3,4,5]. The original array is NOT affectedwith resulting in arraybeing [1,2,3,4,5].

这将返回[3,4,5]。的原始数组不受影响,由此导致array存在[1,2,3,4,5]

Below is simple fiddle which confirms this:

下面是简单的小提琴,证实了这一点:

//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));

//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));


console.log("----after-----");
console.log(array);
console.log(array2);

回答by Gagandeep Gambhir

Splice and Slice both are Javascript Array functions.

Splice 和 Slice 都是 Javascript 数组函数。

Splice vs Slice

拼接与切片

  1. The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.

  2. The splice() method changes the original array and slice() method doesn't change the original array.

  3. The splice() method can take n number of arguments and slice() method takes 2 arguments.

  1. splice() 方法返回数组中删除的项目, slice() 方法返回数组中的选定元素,作为新的数组对象。

  2. splice() 方法更改原始数组,而 slice() 方法不会更改原始数组。

  3. splice() 方法可以接受 n 个参数, slice() 方法可以接受 2 个参数。

Splice with Example

拼接示例

Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

参数 1:索引,必需。一个整数,指定在什么位置添加/删除项目,使用负值指定从数组末尾开始的位置。

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.

参数 2:可选。要删除的项目数。如果设置为 0(零),则不会删除任何项目。如果未通过,将删除所提供索引中的所有项目。

Argument 3…n: Optional. The new item(s) to be added to the array.

参数 3…n:可选。要添加到数组中的新项目。

var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.
 
console.log(array);
// shows [1, 2], original array altered.
 
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
 
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
 
console.log(array2);
// shows [6,7,9,0]

Slice with Example

切片示例

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.

参数 1:必需。一个整数,指定从哪里开始选择(第一个元素的索引为 0)。使用负数从数组的末尾进行选择。

Argument 2: Optional. An integer that specifies where to end the selection but does not include. 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.

参数 2:可选。一个整数,指定结束选择的位置,但不包括。如果省略,将选择从开始位置到数组末尾的所有元素。使用负数从数组的末尾进行选择。

var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
 
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
 
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
 
console.log(array2.slice(-2,4));
// shows [9]
 
console.log(array2.slice(-3,-1));
// shows [8, 9]
 
console.log(array2);
// shows [6, 7, 8, 9, 0]

回答by Alec Kravets

The slice()method returns a copy of a portion of an array into a new array object.

所述切片()方法返回的阵列的一部分的副本到一个新的数组对象。

$scope.participantForms.slice(index, 1);

This does NOTchange the participantFormsarray but returns a new array containing the single element found at the indexposition in the original array.

这并改变participantForms阵列,但返回包含在找到的单个元素的新阵列index的原始数组中的位置。

The splice()method changes the content of an array by removing existing elements and/or adding new elements.

拼接()方法改变阵列的通过去除现有元件和/或添加新元素的内容。

$scope.participantForms.splice(index, 1);

This will remove one element from the participantFormsarray at the indexposition.

这将从participantFormsindex位置的数组中删除一个元素。

These are the Javascript native functions, AngularJS has nothing to do with them.

这些是 Javascript 原生函数,AngularJS 与它们无关。

回答by Sajeetharan

Here is a simple trick to remember the difference between slicevs splice

这是一个简单的技巧来记住slicevs之间的区别splice

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"]

Trick to remember:

Trick to remember:

Think of "spl" (first 3 letters of splice)as short for "specifiy length", that the second argument should be a length not an index

认为是"spl" (first 3 letters of splice)“指定长度”的缩写,第二个参数应该是长度而不是索引

回答by taguenizy

Splice - MDN reference- ECMA-262 spec

拼接 - MDN 参考- ECMA-262 规范

Syntax
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

句法
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters

参数

  • start: required. Initial index.
    If startis negative it is treated as "Math.max((array.length + start), 0)"as per spec (example provided below) effectively from the end of array.
  • deleteCount: optional. Number of elements to be removed (all from startif not provided).
  • item1, item2, ...: optional. Elements to be added to the array from startindex.
  • start: 必需的。初始索引。
    如果start是负数,"Math.max((array.length + start), 0)"则从array.
  • deleteCount: 可选的。要删除的元素数(start如果未提供,则全部来自)。
  • item1, item2, ...: 可选的。要从start索引添加到数组的元素。

Returns: An array with deleted elements (empty array if none removed)

返回:包含已删除元素的数组(如果没有删除元素则为空数组)

Mutate original array: Yes

变异原始数组:是

Examples:

例子:

const array = [1,2,3,4,5];

// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]

// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]

More examples in MDN Splice examples

MDN Splice 示例中的更多示例



Slice - MDN reference- ECMA-262 spec

切片 - MDN 参考- ECMA-262 规范

Syntax
array.slice([begin[, end]])
Parameters

语法
array.slice([begin[, end]])
参数

  • begin: optional. Initial index (default 0).
    If beginis negative it is treated as "Math.max((array.length + begin), 0)"as per spec (example provided below) effectively from the end of array.
  • end: optional. Last index for extraction but not including (default array.length). If endis negative it is treated as "Math.max((array.length + begin),0)"as per spec (example provided below) effectively from the end of array.
  • begin: 可选的。初始索引(默认为 0)。
    如果begin是负数,"Math.max((array.length + begin), 0)"则从array.
  • end: 可选的。提取的最后一个索引但不包括(默认 array.length)。如果end是负数,"Math.max((array.length + begin),0)"则从array.

Returns: An array containing the extracted elements.

返回: 包含提取元素的数组。

Mutate original: No

变异原件:否

Examples:

例子:

const array = [1,2,3,4,5];

// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]

// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]

More examples in MDN Slice examples

MDN Slice 示例中的更多示例

Performance comparison

性能对比

Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test

不要将此视为绝对真理,因为根据每种情况,一个可能比另一个更好。
性能测试

回答by mrunion

Splice and Slice are built-in Javascript commands -- not specifically AngularJS commands. Slice returns array elements from the "start" up until just before the "end" specifiers. Splice mutates the actual array, and starts at the "start" and keeps the number of elements specified. Google has plenty of info on this, just search.

Splice 和 Slice 是内置的 Javascript 命令——不是专门的 AngularJS 命令。Slice 返回从“开始”到“结束”说明符之前的数组元素。Splice 改变实际数组,并从“开始”开始并保持指定的元素数量。谷歌有很多关于这方面的信息,只需搜索。

回答by Ranjith Ayyadurai

The splice()method returns the removed items in an array. The slice()method returns the selected element(s) in an array, as a new array object.

splice()方法返回数组中删除的项目。该slice()方法返回数组中选定的元素,作为一个新的数组对象。

The splice()method changes the original array and slice()method doesn't change the original array.

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.

  • Splice()方法可以接受 n 个参数:

    参数 1:索引,必需。

    参数 2:可选。要删除的项目数。如果设置为 0(零),则不会删除任何项目。如果未通过,将删除所提供索引中的所有项目。

    参数 3..n:可选。要添加到数组中的新项目。

  • slice()方法可以接受 2 个参数:

    参数 1:必需。一个整数,指定从哪里开始选择(第一个元素的索引为 0)。使用负数从数组的末尾进行选择。

    参数 2:可选。一个整数,指定结束选择的位置。如果省略,将选择从开始位置到数组末尾的所有元素。使用负数从数组的末尾进行选择。

回答by xgqfrms

splice & delete Array item by index

按索引拼接和删除数组项

index = 2

指数 = 2

//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]

console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));

console.log("----after-----");
console.log(arr1);
console.log(arr2);

let log = console.log;

//splice & will modify the origin array
const arr1 = [1,2,3,4,5];

//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]

log("----before-----");
log(arr1.splice(2, 1));
log(arr2.slice(2, 1));

log("----after-----");
log(arr1);
log(arr2);

enter image description here

在此处输入图片说明

回答by dev verma

slice does not change original array it return new array but splice changes the original array.

slice 不改变原始数组它返回新数组但 splice 改变原始数组。

example: var arr = [1,2,3,4,5,6,7,8];
         arr.slice(1,3); // output [2,3] and original array remain same.
         arr.splice(1,3); // output [2,3,4] and original array changed to [1,5,6,7,8].

splice method second argument is different from slice method. second argument in splice represent count of elements to remove and in slice it represent end index.

splice 方法的第二个参数与 slice 方法不同。splice 中的第二个参数表示要删除的元素数,在 slice 中它表示结束索引。

arr.splice(-3,-1); // output [] second argument value should be greater then 
0.
arr.splice(-3,-1); // output [6,7] index in minus represent start from last.

-1 represent last element so it start from -3 to -1. Above are major difference between splice and slice method.

-1 代表最后一个元素,所以它从 -3 到 -1。以上是拼接和切片方法之间的主要区别。

回答by Jakub Kubista

Another example:

另一个例子:

[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]

[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]