The difference between the three methods of splice(), slice(), and split() in JavaScript, and the detailed usage

Introduction: splice, slice, and split are three commonly used methods in JavaScript. They look similar on the surface, but their uses are quite different. Today, I will introduce their usages respectively.

1. splice() method

The splice method can be used to remove elements from an array, or to add new elements to an array. Its syntax is as follows:


array.splice(start, deleteCount, item1, item2, ...)

Among them, start indicates the starting position of the element to be deleted or added, deleteCount indicates the number of elements to be deleted, and item1, item2, etc. indicate the elements to be added to the array.

Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi"); 

console.log(fruits); 
// ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]

In the code above, we start at the second position of the array, delete one element (i.e. "Apple"), and add two new elements (i.e. "Lemon" and "Kiwi") to the array.

2, slice () method

The slice method can be used to extract some elements from an array and return a new array. Its syntax is as follows:


array.slice(start, end)

Among them, start indicates the starting position to be extracted, and end indicates the end position to be extracted (excluding elements at this position).

Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var citrus = fruits.slice(1, 3); 

console.log(citrus); 
// ["Orange", "Apple"]

fruits.slice(-1); //表示截取数组最后一项

In the above code, starting from the first position of the array, we extracted two elements (i.e. "Orange" and "Apple") and stored them in a new array.

3. split() method

The split method can be used to split a string into an array. Its syntax is as follows:


string.split(separator, limit)

Among them, separator indicates the character or character string used to divide the string, and limit indicates the maximum length of the returned array.

Example:

var str = "How are you doing today?";
var words = str.split(" "); //从空格部分开始分割

console.log(words); 
// ["How", "are", "you", "doing", "today?"]

In the above code, we split a string into an array according to spaces and store it in the variable words.

If you find it useful, just click three times, thank you (●'◡'●)

Guess you like

Origin blog.csdn.net/weixin_65793170/article/details/130744225