slice(),splice(),split(),substring(),substr()的分析
slice() 数组和字符串都有
不改变原数组,
// slice(start ,end)
var str="wuhu aizai!"
var arr=['one','two','three','four','five']
console.log(arr.slice(1));//[ 'two', 'three', 'four', 'five' ]
console.log(arr.slice(1,3));//[ 'two', 'three' ]
console.log(arr.slice(-3));//[ 'three', 'four', 'five' ]
console.log(arr.slice(-3,4));//[ 'three', 'four' ]
console.log(str.slice(1));//uhu aizai
console.log(str.slice(1,5));//uhu
console.log(str.slice(-3));//ai!
console.log(str.slice(-3,5));//null a>b
splice() 数组的方法
返回新的数组,改变原数组的值
splice(start,length,[替换的数组])
var arr=['one','two','three','four','five']
// console.log(arr.splice(1)); //['two','three','four','five']
// console.log(arr); //['one']
console.log(arr.splice(1, 0, 'hello', 'wuwu')); //[]
console.log(arr); //['one', 'hello', 'wuwu','two','three','four','five']
console.log(arr.splice(2, 3, 'haha')); //[ 'wuwu', 'two', 'three' ]
console.log(arr); //[ 'one', 'hello', 'wuwu', 'two', 'three', 'four', 'five' ]
split() 字符串的方法
不改变原字符串
(把字符串分割成数组)
split 两个参数(分隔符(必写),number(返回参数个数,可选))
return []
var str="hello enheng jdkw";
console.log(str.split(''));
//[ 'h', 'e', 'l', 'l', 'o', ' ', 'e', 'n', 'h', 'e', 'n', 'g', ' ', 'j', 'd', 'k', 'w' ]
console.log(str.split(' '));
//[ 'hello', 'enheng', 'jdkw' ]
console.log(str.split(" ",2))
// [ 'hello', 'enheng' ]
console.log(str);
substring
substring(start,end);
返回一个新的字符串,[start,end) 不改变原数组的值
- start==end 返回空串
- start>end 交换两个参数,然后截取
- start或end有一个是负数,那么用0替代他
var str1='abcdefghig';
console.log(str1.substring(1));
console.log(str1.substring(1,6));
console.log(str1.substring(8,6));
console.log(str1.substring(8,-2));
console.log(str1);
substr
substr(start[,length])
start为负数,从字符串后面取值
length=0或者负数,返回一个空的字符串
如果没有指定该参数,则子字符串将延续到stringObject的最后
console.log(str1.substr(1));//bcdefghig
console.log(str1.substr(1,2));//bc
console.log(str1.substr(1,-1));//null