JS常用数组和字符串相关操作:数组增加、删除、截取、剪切、合并、翻转,取下标以及字符串截取、分割等
每次对数组进行相关操作时,会发现总是混淆一些功能如slice即可截取数组也可截取字符串,splice(数组)split(字符串)不太容易区分,下面就对数组和字符串进行细分
数组
1.删除第一项,shift
var arr=['a','b','c','d','e','f'];
arr.shift(); //arr=['b','c','d','e','f']
arr.shift(); //arr=['c','d','e','f']
2.删除最后一项,pop
var arr=['a','b','c','d','e','f'];
arr.pop(); //arr=['a','b','c','d','e']
arr.pop(); //arr=['a','b','c','d']
arr.pop(); //arr=['a','b','c']
3.从最后一项添加,push
var arr=['a','b','c','d','e','f'];
arr.push(1); //arr=['a','b','c','d','e','f',1]
arr.push(2); //arr=['a','b','c','d','e','f',1,2]
4.从第一项添加,unshift
var arr=['a','b','c','d','e','f'];
arr.unshift(1); //arr=[1,'a','b','c','d','e','f']
arr.unshift(2); //arr=[2,1,'a','b','c','d','e','f']
arr.unshift(3); //arr=[3,2,1,'a','b','c','d','e','f']
5.数组翻转,reverse
var arr=['a','b','c','d','e','f'];
arr.reverse(1); //arr=['f','e','d','c','b','a']
6.数组合并,concat
var arr=['a','b','c','d','e','f'],bb=[1,2,3];
var cc=arr.concat(bb); //cc=['a','b','c','d','e','f',1,2,3]
7.数组下标(索引),indexof
var arr=['a','b','c','d','e','f'];
arr.indexof(b); // 1
arr.indexof('b'); // -1
arr.indexof(d); // 3
8.数组转换字符串,join
var arr=['a','b','c','d','e','f'];
var b= arr.join('-'); // b='a-b-c-d-e-f';
9.数组截取(原数组未发生变化),slice,返回从原数组中指定start(包含)到end(不包含)之间的项组成的数组,原数组未发生变化
var arr=['a','b','c','d','e','f'];
var b= arr.slice(1,2); // b=['b']; arr=['a','b','c','d','e','f'];
var b= arr.slice(0,3); // b=['a','b','c']; arr=['a','b','c','d','e','f'];
10.数组剪切(原数组发生变化),splice,第一个参数为start,第二个参数为剪切个数,从第三个开始为添加项
var arr=['a','b','c','d','e','f'];
arr.splice(0,3); // arr=['a','b','c']
arr.splice(arr.length-1,1); //arr=['a','b','c','d','e'];
arr.splice(1,1,20,25); //arr=['a',20,25,'c','d','e'];
//当从最后元素开始,剪切个数为任意个是,则为添加
arr.splice(arr.length,35,20); //arr=['a','b','c','d','e',20];
//当从第一个元素开始,截取0个长度时,则从头部添加
arr.splice(0,0,20,21); //arr=[20,21,'a','b','c','d','e']
字符串
1.字符串截取(原字符串不变),slice,从字符串中下标,start(包含)到end(不包含)之间的字符串
var aa='A hello';
var b=aa.slice(0,4); //'A he'
2.字符串分割,split
var aa='23456';
var b=aa.split('',2); //'23'
var b=aa.split('23',2); //'456'
3.字符串获取最后一位
3.1通过charAt()获取
var a="23456";
var b=a.charAt(a.length-1);// b=1
3.2通过substr()获取
var a="23456";
var b=a.substr(a.length-1,1);// b=1
3.2通过split()获取
var a="23456";
var b=a.split("");
alert(b[b.length-1]);// 6