The difference between substr and substring, slice and splice, js string interception and array interception

This article refers to the article: https://blog.csdn.net/kenberkeley/article/details/50983734

The blogger has summed it up very well, and I can understand it after reading it, but I still feel that I need to knock it on my own to deepen my understanding and record it, so I have this blog

 

First of all, substring and substr , you can see that str refers to a string by looking at the word, so they are both functions that intercept strings, and both return a copy of the original string without changing the original string

var str = "012345678";
console.log(str.substring( 1)); // 12345678 If the second parameter is empty, it will be intercepted to the end by default 
console.log(str.substring(1,4)); // 123, 1 means the start Subscript, 4 means the cutoff subscript 

console.log(str.substr( 1)); // 12345678 If the second parameter is empty, it will be intercepted to the end by default 
console.log(str.substr(1,4)) // 1234 , 1 represents the starting subscript, 4 represents the interception length 
console.log( str.substr(-4) ); // 5678, a negative number can be accepted, the last four digits of the interception 

console.log(str); // 012345678, the original array does not change

in conclusion,

sunstring($1,$2) , $1 refers to the starting subscript, $2 refers to the ending subscript, so the interception interval is [$1,$2]

substr($1,$2) , $1 also refers to the starting subscript, the difference is that $2 refers to the interception length, so the interception interval is [$1,$1+$2-1]

 

Second: slice and spice operate on arrays (slice can also be used for strings), the return value is an array, slice does not change the original array, splice operates directly on the original array (operates directly on the array) and pop/push/shift/unshift/sort/reverse/concat)

var arr = [0,1,2,3,4,5,6,7 ]
console.log(arr.slice( 1)); // [1, 2, 3, 4, 5, 6, 7] If the second parameter is empty, it will be intercepted to the end by default 
console.log(arr.slice(1 ,4)); // [1, 2, 3], 1 is the start index, 4 is the end index 
console.log(arr) //   [0, 1, 2, 3, 4, 5, 6, 7] The original array is unchanged 

console.log(arr.splice( 1,4)); // [5, 6, 7] 
console.log(arr); // [0, 5, 6, 7] except by splice The intercepted part, the original array still has these few

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325251322&siteId=291194637