JS数组的几个常用方法
1. join() 将数组拼接成字符串;
var a = [1,2,4,5];
var b = a.join()
console.log(b)// '1245'
2. split() 将字符串拆分为数组;
var a = 'hello timy'
var b = a.split();
console.log(b);//["h", "e", "l", "l", "o", " ", "t", "i", "m", "y"]
*join()与split()属于逆向转换;
3. reverse() 将数组中的元素顺序颠倒;
var a = [1,2,3];
a.reverse();
console.log(a);//[3,2,1]
4. sort() 将数组中的元素排序并返回排序后的数组;
var a = ['cde','bed','abc'];
a.sort();
console.log(a);//["abc", "bed", "cde"]
如果数组中包含undefined元素,它们会排到数组尾部;
默认按字母表顺序;
var a = [33,4,111,22];
a.sort();
console.log(a);//[111, 22, 33, 4]
从小到大排列
a.sort(function(a,b){return a-b});
console.log(a);//[4, 22, 33, 111]
从大到小排列
a.sort(function(a,b){return b-a});
console.log(a);//[111, 33, 22, 4]
区分大小写的排序;
a = ['ant','Bug','cat','Dog'];
a.sort();
console.log(a);//["Bug", "Dog", "ant", "cat"]
不区分大小写的排序;
a.sort(function(s,t){
var a = s.toLowerCase();
var b = t.toLowerCase();
if(a<b) return -1;
if(a>b) return 1;
return 0;
});
console.log(a);//["ant", "Bug", "cat", "Dog"]
5. concat() 创建并返回一个新数组;不改变数组,用完就释放了;
var a = [1,2,3];
a.concat(4,5); //[1,2,3,4,5]
console.log(a);//[1,2,3];
a.concat([4,5]);//[1,2,3,4,5]
a.concat([4,5],[6,7]);//[1,2,3,4,5,6,7]
a.concat(4,[5,[6,7]]);//[1,2,3,4,5,[6,7]
6. slice() 指定数组的一个片段或子数组;它的两个参数分别是片段的开始和结束;不改变数组,用完就释放;
var a = [1,2,3,4,5];
a.slice(0,3);//[1,2,3]
a.slice(3);//[4,5];
a.slice(1,-1);//[2,3,4];
a,slice(-3,-2);//[3]
console.log(a);// [1,2,3,4,5]
7. splice() 在数组中插入或删除元素的通用方法;会修改数组;第一个参数表示开始截取位置,二个参数表示截取数量;还有多位参数看下面例子;
var a = [1,2,3,4,5,6,7,8,9];
var b = a.splice(4);;//[5,6,7,8,9];
console.log(a);//[1,2,3,4]
var c = a.splice(1,2);//[2,3];
console.log(a);//[1,4]
var d = a.splice(1,1);//[4]
console.log(a);//[1]
既然能删除,当然还会有插入;第一个参数表示插入位置,第二个参数表示替换几位;后面的参数
var a = [1,2,3,4,5];
a.splice(2,0,'a','b','c'); //[1, 2, "a", "b", "c", 3, 4, 5]
a.splice(3,3,6,7,8,9); //[1, 2, "a", 6, 7, 8, 9, 4, 5]
a.splice(3,0,[2,3,4]);//[1, 2, "a", [2,3,4], 6, 7, 8, 9, 4, 5]
注意:与concat()不同的,splice()会插入数组本身而非数组的元素
8. push() 和pop(),在数组的尾部添加一个或多个元素,删除最后一个元素;
var a = [];
a.push(1,2);
console.log(a);//[1,2]
a.push('a','b');
console.log(a);//[1,2,'a','b']
a.pop();
console.log(a);//[1, 3, "a"]
9. unshift() 和 shift() ,在数组的头部添加一个或多个元素,删除一个元素;
var a = [2,3];
a.unshift(1);
console.log(a);//[1,2,3];
a.unshift('a','b');
console.log(a);//["a", "b", 1, 2, 3]
a.shift();
console.log(a);//["b", 1, 2, 3]
10. toString() 和 toLocaleString()
var a = ["b", 1, 2, 3]
var b = a.toString();
var c = a.toLocaleString();
console.log(a);//["b", 1, 2, 3]
console.log(b);//b,1,2,3
console.log(c);//b,1,2,3