substr、substring、slice、splice的用法区别

var str1 = "abcdef"
var arr1 = ["a","b","c","d","e","f"]

console.log( str1.substr(0,3) );        //"abc",从下标0开始,截取3个字符
console.log( str1.substring(0,3) );     //"abc",从下标0开始,下标3结束,不包括下标3
console.log( str1.slice(0,3) );         //"abc",从下标0开始,下标3结束,不包括下标3
console.log( str1.splice(0,3) );        //字符串没有此方法
  
!字符串没有splice()方法!,slice和substring的不同在于,substring可以写成(3,0),结果一样,而slice不行。


console.log( arr1.substr(0,3) );        //数组没有此方法
console.log( arr1.substring(0,3) );     //数组没有此方法
console.log( arr1.slice(0,3) );    //"abc",从下标0开始,下标3结束,不包括下标3 ,不能反写为(3,0)
console.log( arr1.splice(1,3) );  //从下标1开始,取3个出来,原数组会改变,可加第三个参数填写新数

猜你喜欢

转载自blog.csdn.net/qq_36414265/article/details/81112899