数组的方法有许多,但来来回回常用的也就那几种,特此记录,以备遗忘之需。
将数组合并成字符串
- toString()
直接把数组里的内容变成一个字符串
var arr = [12,25,30,92]; var arr1 = arr.toString(); //arr1 = 12,25,30,92
- join()
以某种符号将数组内容串联成一个字符串
var arr = [12,25,30,92]; var arr1 = arr.join('*'); //arr1 = 12*25*30*92
增加数组内容
1.push()
添加的内容按顺序放在数组最后面,并自动加长度
var arr = [12,25,30,92];
var arr1 = arr.push(51,65); //arr1 = [12,25,30,92,51,65]
2.unshift()
添加的内容按顺序放在数组的最前面,并自动增加长度
var arr = [12,25,30,92];
var arr1 = arr.unshift(51,65); //arr1 = [51,65,12,25,30,92]
取出数组内容
1.pop()
取出数组最后一个元素,并返回该值且在数组中消失
var arr = [12,25,30,92];
var poped = arr.pop();
//arr = [12,25,30] poped = 92
2.shift()
取出数组第一个元素,并返回该值且在数组中消失
var arr = [12,25,30,92];
var shifted = arr.shift();
//arr = [25,30,92] shifted = 12
3.slice(begin,end)
浅复制了数组内容,begin为开始复制的位置,end为结束复制的位置
var arr = [12,25,30,92];
var arr1 = arr.slice(1,3);
//arr1 = [25,30,92]
排序
排序的方法倒是只有一种,即sort(),但是分为升序和降序
1.升序
默认为升序
var arr = [12,0,25,30,92];
var arr1 = arr.sort();
//arr1 = [0,12,25,30,92]
还有另一种写法记得ab不能写反
var arr = [12,0,25,30,92];
var arr1 = arr.sort(functiion(a,b){
return a-b;
});
//arr1 = [0,12,25,30,92]
2.降序
var arr = [12,0,25,30,92];
var arr1 = arr.sort(functiion(a,b){
return b-a;
});
//arr1 = [92,30,25,12,0]
替换数组内容
splice(start,items,inplace);此方法从数组的start位置开始删除items个元素,并添加inplace元素
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']
// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']
// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']
// removes 2 elements from index 2
removed = myFish.splice(myFish.length -3, 2);
// myFish is ['parrot', 'anemone', 'surgeon']
// removed is ['blue', 'trumpet']
这一个引用了devdocs的demo
合并数组
concat();将两个数组合并成一个新数组,并返回该数组
var arr1 = [12,23,34];
var arr2 = ['hello','world'];
var arr3 =arr1.concat(arr2);
//arr3 = [12,23,34,'hello','world']
哪个数组使用了此方法,哪个就在前
网友评论