接着上面,继续数组方法
字符串转数组:
var s="abcdefj"
var arr=s.split(""); //["a","b","c","d","e","f","j"]
截取数组:slice()
var arr=["a","b","c"]
var brr=arr.slice(0); //["a","b","c"]
var brr=arr.slice();
var brr=arr.slice(1); //["b","c"]
var brr=arr.slice(1,2) //["b"]
var brr=arr.slice(2,8) //["c"]
删除或替换:splice()
function szff(){
var s="abcdefj"
var arr=s.split("");
var brr=arr.splice(3,2); //["d","e"] 这时候arr=["a","b","c","f","j"]
var drr=arr.splice(2,0,"x","y") //["a","b","x","y","c","f","j"]
}
数组排序(reverse/sort)
var arr=["a","z","d","f","b"];
arr.resver(); //["b","f","d","z","a"]
sort()默认按字典顺序排序,可以自定义排序
查找元素的位置(indexOf/lastIndexOf)
var arr=["a","b","c"];
var i=arr.indexOf("b"); //i=1
var j=arr.indexOf("z"); //j=-1
var t=arr.indexOf("a",1); //t=-1,从1号位开始找,到不到,就返回-1
用来判断一个元素是否在一个数组中,只需判断大于0即可。
现在一般用includes()方法来判断。
|