(1) shift
删除数组第一个元素,并返回该元素,跟pop差不多
var arr=[1,2,1,3,2,3,5,6,5];
arr.shift();
console.log(arr); //[2, 1, 3, 2, 3, 5, 6, 5]
(2) unshift
跟shift相反,往数组最前面添加元素,并返回数组新长度
var arr=[1,2,1,3,2,3,5,6,5];
arr.unshift('haha');
console.log(arr); //["haha", 1, 2, 1, 3, 2, 3, 5, 6, 5]
(3) concat
在现有数组后面追加数组,并返回新数组,不影响现有数组
var arr=[1,2,1,3,2,3,5,6,5];
var arr1=['hahha'];
console.log(arr.concat(arr1));//[1, 2, 1, 3, 2, 3, 5, 6, 5, "hahha"]
(4) join
用指定间隔符连起来,把数组转为字符串
var arr=[1,2,1,3,2,3,5,6,5];
console.log(arr.join()); //1,2,1,3,2,3,5,6,5
console.log(arr.toString())//1,2,1,3,2,3,5,6,5toString()也可以
console.log(arr.join('*'))//1*2*1*3*2*3*5*6*5
(5) pop
删除数组最后一个元素,并返回该元素
var a = ["aa","bb","cc"];
console.log(a.pop()) //cc
console.log(a) //["aa", "bb"]
(6) reverse
对数组进行反排序跟,sort()一样,取第一字符ASCII值进行比较
var a = ["aa","bb","cc"];
console.log(a.reverse()); //["cc", "bb", "aa"]
console.log(a) //["cc", "bb", "aa"]
(7) slice
返回数组片段
var a = ["aa","bb","cc"];
console.log(a.slice(1,2)) //["bb"]从第一个开始到第二个,但不包含第二个
console.log(a.slice(1)) //["bb", "cc"]
数组方法小试牛刀
- 翻转字符串
console.log("asd".split("")) //["a", "s", "d"]
console.log("asd".split("").reverse().join()) //d,s,a
- [1,2,1,3,2,3,5,6,5] 去除重复元素
var arr=[1,2,1,3,2,3,5,6,5];
var newarr=[];
for(var i=0;i<arr.length;i++){
if(newarr.indexOf(arr[i])==-1){
newarr.push(arr[i]);
}
}
console.log(newarr)//[1, 2, 3, 5, 6]
3.获取里面字面最多的字母
var str = "asdfjksdjfljsdflkjsdjf" //定义需要判断的字符串
var maxlength = 0; //用来存最大数量的变量,并初始化为0
var result; //用来接收结果
while(str != ""){
var oldstr = str;
var getstr = str.substr(0,1);
str = str.replace(new RegExp(getstr,"g"),"");
if(oldstr.length - str.length >maxlength){
maxlength = oldstr.length - str.length;
result = getstr + '='+ maxlength;
}
}
console.log(result);