1.数组转字符串
方法一:数组.join("连接符"),连接符自定义。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x= fruits.join(',');
var y= fruits.join('-');
console.log(x);
console.log(y);
方法二:数组.toString(),","连接。
当方法一连接符指定","时,方法一和方法二效果相同。
2.操作数组末尾,push()和pop()
push()在数组末尾添加元素:
var arr = ["a","b","c"];
arr.push("d","e");
console.log(arr);
pop()从数组末尾删除元素:
var arr = ["a","b","c"];
arr.pop();
console.log(arr);
3.操作数组开头,shift() 和 unshift()
shift()从数组开头删除元素,并返回被删除的元素:
var arr = ["a","b","c"];
console.log(arr.shift());
console.log(arr);
如果数组为空则返回undefined
unshift()从数组开头添加元素:
4.splice():删除、插入和替换
删除:splice(x,y),x是要删除元素的起始位置,y是元素个数。
//从位置0开始删除2个元素
var arr = ["a","b","c","d","e"];
arrdeleted=arr.splice(0,2)
console.log(arrdeleted);
console.log(arr);
插入:splice(x,0,z),x是起始位置指定位置,0是删除的元素个数,即删除0项,z是添加的任意数量元素。
//从位置2开始,删除0个元素,添加元素"e","f"
var arr = ["a","b","c","d","e"];
arr.splice(2,0,"e","f")
console.log(arr);
替换:splice(x,y,z),x是起始位置指定位置,y是删除的元素个数,z是添加的任意数量元素,y不必等于z。
//从位置2开始,删除3个元素,添加元素"f","g"
var arr = ["a","b","c","d","e"];
arr.splice(2,2,"f","g")
console.log(arr);
5.reverse():反转数组项的顺序,直接改变数组。
var arr = [13, 24, 51, 3];
console.log(arr.reverse());
console.log(arr);
6.concat():添加数组元素。
var arr = [1,3,5,7];
console.log(arr.concat(9,'a','b'));
7.slice():数组切片。
var arr = [1,3,5,7,9,11];
var arr1 = arr.slice(1);
var arr2 = arr.slice(1,-2);
var arr3 = arr.slice(-4,-1);
var arr4 = arr.slice(-3);
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
8.forEach():遍历数组元素和索引。
arr = ['a', 'b', 'c', 'd','e' ];
arr.forEach(function (x, index) {
console.log(x, index);
});
9.map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组(类python列表生成式的效果)。
var arr = [1, 2, 3, 4, 5];
var arr1 = arr.map(function(value){
return value*10;
});
console.log(arr1);
10.filter():过滤,数组中的每一项运行给定函数,返回满足过滤条件组成的数组。
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arr1 = arr.filter(function(x, i) {
return i % 3 === 0 & x >= 5;
});
console.log(arr1);
11.evey()和some():evey:判断数组中每一项都是否满足条件,只有所有项都满足条件,才会返回true;some:判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true。