关于数组的一些方法。
1、splice()
var arr = [1,2,3,4,5,6]; //删除:splice(起点,长度); arr.splice(2,3);//从第二项开始,删除三个 console.log(arr);//结果是1,2,6
var arr = [1,2,3,4,5,6]; //插入:splice(起点,长度,被插入的元素); arr.splice(2,1,'a','b','c');//从第二项开始,删除一个,然后在删除的位置添加abc三个元素 console.log(arr);//结果是[1, 2, "a", "b", "c", 4, 5, 6]
2、concat()
var a = [1,2,3]; var b = [4,5,6]; console.log(a.concat(b));//数组连接 //结果是[1, 2, 3, 4, 5, 6]
var arr = [1,2,3,4,5]; console.log(arr.join("::"));//数组分隔符 //结果是1::2::3::4::5
3、sort()
var arr = ['e','d','f','z','a','c','v']; console.log(arr.sort());//数组按照字母排序 //结果是["a", "c", "d", "e", "f", "v", "z"]
1 var arr = [112,32,21,53,23]; 2 console.log(arr.sort(function(n1,n2){ 3 if(n1<n2){ 4 return -1; 5 }else if(n1>n2){ 6 return 1; 7 }else{ 8 return 0 9 } 10 })); 11 //比较数字
化简之后
var arr = [112,32,21,53,23]; console.log(arr.sort(function(n1,n2){ return n1-n2; }));