Usage and differences between splice() and split()

splice() and split() are common methods for strings and arrays in JavaScript

1.splice()

splice() is used to add/remove/replace elements in an array, it will directly modify the original array . Its basic syntax is as follows:

1.1·Delete elements

array.splice(start,deleteCount): Starting from the start index, delete deleteCount elements and return a new array composed of deleted elements; if the deleteCount parameter is default, delete all elements from the start index to the end of the array.
Example :

const arr = [1,2,3,4];
const deleted = arr.splice(1,2)
console.log(arr); // 输出[1,4]
console.log(deleted ); // 输出[2,3]

1.2·Insert elements

array.splice(start,0,item1,item2,…): Starting from the start index, insert the specified new element into the array, and return the deleted elements to form a new array. If the deleteCount parameter is 0, only new elements will be inserted. element.
example:

const arr = [1,2,3,4];
const deleted = arr.splice(1,0,4,5)
console.log(arr); // 输出[1,4,5,2,3]

1.3·Replace elements

array.splice(start,deleteCount,item1,item2,…): Starting from the start index, delete deleteCount elements, insert the specified new elements into the array, and return a new array composed of deleted elements. If the deleteCount parameter is 0, only new elements will be inserted
. Example:

const arr = [1,2,3,4];
const deleted = arr.splice(1,2,5,6)
console.log(arr); // 输出[1,5,6,4]
console.log(deleted ); // 输出[2,3]

It should be noted that the splice() method will directly modify the original array and return a new array composed of deleted elements. If incorrect parameters are passed, unexpected results may occur, so it is recommended that when using this method, you carefully check whether the operation is correct and perform a backup operation if necessary.

2.split()

The split() method is used to convert a string into an array according to the specified delimiter. Its basic syntax is as follows:

string.split(separator,limit);

Among them, separator represents the separator, which can be a string or a regular expression. If omitted, it means using a space as the separator; limit represents the maximum number of divisions, if omitted, there is no limit.
For example, the following example converts the string "one, two, three" separated by commas "," into an array:

const str = "one,two,three";
const arr = str.split(",");
console.log(arr); // 输出["one","two","three"]

Guess you like

Origin blog.csdn.net/weixin_56733569/article/details/130729756