当前位置:网站首页>The difference between slice() and slice()

The difference between slice() and slice()

2022-07-23 11:32:00 Superman can't fly~~

Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right

List of articles


One 、slice

slice(start,end): Method returns the selected element from an existing array , Returns a new array , Contains from start To end( Does not contain the element ) Array elements of .

Be careful : This method does not change the original array , Instead, it returns a sub array , If you want to delete an element in an array , You should use Array.splice() Method .

  • start Parameters : must , Specify where to start selecting , If it's negative , Specify the position from the end of the array ,-1 Refers to the last element .
  • end Parameters : Optional ( If the parameter is not specified , So the sharded array contains from start The end of all elements of the inverted array , If this parameter is negative , So the rule is the element counting from the end of the array ).
var arr = [1,2,3,4,5];
console.log(arr.slice(1));//[2,3,4,5]  Select the serial number from 1 To a new array of all the last elements .
console.log(arr.slice(1,3))//[2,3]  It doesn't contain end, Serial number for 3 The elements of 

meanwhile slice(start,end) Can act on the cutting of string

/* String cutting and extraction ----slice(start,end),substring(),substr()*/
var str = "Hello,world!";
var sliceStr = str.slice(1,5);//ello ( It doesn't contain end)
var subStr = str.substring(1,5);//ello
var subStr = str.substr(1,5);//ello,
var str = "1000000";
var sliceStr = str.slice(-3);//000  From serial number to -3 To the end 

2.splice

2.splice(): This method adds or removes items to or from the array , Returns the deleted item .( This method will change the original array )
splice(index,howmany,item1,…itemX)

  • index Parameters : must , Integers , Specify where to add or delete , Use negative numbers , Specify the position from the end of the array .
  • howmany Parameters : must , Quantity to delete , If 0, The item is not deleted .
  • tem1,…itemX Parameters : Optional , New items added to array .
var arr = [1,2,3,4,5];
console.log(arr.splice(2,1,"hello"));//[3]  New array returned 
console.log(arr);//[1, 2, "hello", 4, 5]  Changed the original array 
原网站

版权声明
本文为[Superman can't fly~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230537453383.html