当前位置:网站首页>Introduction to the use of splice() method

Introduction to the use of splice() method

2022-06-24 10:37:00 Yansuizi blog

Catalog

1. Delete any number of items

2. add to : You can add any item to the specified location

 3. Replace ( Delete and add ): You can add any item to the specified location , Delete any number of items at the same time .

4. It is also possible not to receive a return value


Let's start with an array

var str = ["red","yellow","black","lime","pink","gary"];

1. Delete any number of items

Just pass in two parameters . The location of the first item to delete and the number of items to delete

var con = str.splice(1,1);      // Delete the second item 
console.log(str);   //["red", "black", "lime", "pink", "gary"]
console.log(con);   //["yellow"]

2. add to : You can add any item to the specified location

You only need to provide three parameters : The starting position ,0( Number of items to delete ) And the items to add . If you want to add multiple items, you can continue to write parameters after them, separated by commas .

var con = str.splice(1,0,"orange","blue");      // From the position 1 Start push 1 term 
console.log(str);   // ["red", "orange", "blue", "black", "lime", "pink", "gary"]
console.log(con);   // []

 3. Replace ( Delete and add ): You can add any item to the specified location , Delete any number of items at the same time .

You need to specify three parameters : The starting position , Number of items deleted and items to be added , The number of items added should not be consistent with the number of items deleted .

 var con = str.splice(1,2,"blue");      // Delete the second item   Then push... In the deleted position 1 term 
  console.log(str);   // ["red", "blue", "black", "lime", "pink", "gary"]
  console.log(con);   // ["orange", "blue"]

4. It is also possible not to receive a return value

str.splice(0,3,"red");
 console.log(str);   // ["red", "lime", "pink", "gary"]

summary :

1.splice() Method always returns an array , The array contains items that were removed from the original array , If nothing is deleted , Then an empty array will be returned .

2. Be careful The method and slice() It's different ,splice() Will modify the items in the original array .

3. If the parameter is a negative number, output the original array , No operation .

原网站

版权声明
本文为[Yansuizi blog]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240928489037.html