1、创建数组
//创建数组
var arr1=new Array()
var arr2=[]
2、检测数组
(1)判断对象的constructor是否指向Array,接着判断特殊的属性length,splice等。(应用的是construtor的定义:返回对象所定义的构造函数)
var arr=[]
console.log(arr.constructor==Array)//true
(2)使用instanceof
var arr=[]
console.log(arr instanceof Array) //true
(3)最优方式:Object.prototype.toString().call(arr)===[‘object Array’]
(4)Array.isArray()
var arr=[]
console.log(Array.isArray(arr))//true
3、转换数组
(1)toString()
(2)valueOf()
(3)toLocaleString()
(4)join()
var colors=["red","yellow","blue"]
console.log(colors.toString())//red,yellow,blue
console.log(colors.toLocaleString())//red,yellow,blue
console.log(colors.valueOf())//["red", "yellow", "blue"]
console.log(colors.join("||"))//red||yellow||blue
4、位置方法
var arr7=[1,2,3,4,5,6]
console.log(arr7.indexOf(3))//2
console.log(arr7.lastIndexOf(5))//4
5、改变原数组的方法
(1)push() 和 pop()
//push()和pop()
var arr1=[1,2,3]
console.log(arr1.push(5))//4 返回数组的length值
console.log(arr1)//[1, 2, 3, 5]
console.log(arr1.pop())//5 返回被删除的一项
console.log(arr1)//[1, 2, 3]
(2)shift() 和unshift()
//shift和unshift()
var arr2=[1,2,3]
console.log(arr2.shift())//1 返回被删除的一项
console.log(arr2)//[2,3]
console.log(arr2.unshift(5))//3 返回数组的长度
console.log(arr2)//[5,2,3]
(3)重排序
//reverse()和sort()
var arr3=[1,2,12,45,5,23,3,4,5,6]
arr3.reverse()
console.log(arr3)//[6, 5, 4, 3, 23, 5, 45, 12, 2, 1]
arr3.sort()
console.log(arr3)//[1, 12, 2, 23, 3, 4, 45, 5, 5, 6]
function compare(v1,v2){
if(v1>v2){
return 1
}
else if(v1<v2){
return -1
}
else{
return 0
}
}
arr3.sort(compare)
console.log(arr3)//[1, 2, 3, 4, 5, 5, 6, 12, 23, 45]
(4)splice()
//splice()
var arr6=[1,2,3,4,5,6,7]
var arr6b=[1,2,3,4,5,6,7]
var arr6a=[1,2,3,4,5,6,7]
//删除 splice(删除的第一项位置,删除的项数))
var remove=arr6.splice(1,4)
console.log(arr6)//[1,6,7]
console.log(remove)//[2,3,4,5]
//插入 splice(起始位置,0,要插入的项))
var insert1=arr6b.splice(2,0,3)
console.log(arr6b)//[1, 2, 3, 3, 4, 5, 6, 7]
console.log(insert1)//[]
//替换 splice(起始位置,要删除的项数,插入项)
var rep=arr6a.splice(2,2,0,0,0)
console.log(arr6a)//[1, 2, 0, 0, 0, 5, 6, 7]
console.log(rep)//[3,4]
6、不改变原数组
(1)concat()
var arr4=[1,2,3,4]
var arr4a=arr4.concat(5,6)
console.log(arr4a)//[1,2,3,4,5,6]
(2)slice()
//slice()截取
var arr5=[1,2,3,4,5,6,7]
var arr5a=arr5.slice(1)
var arr5b=arr5.slice(1,4)
console.log(arr5a)//[2, 3, 4, 5, 6, 7]
console.log(arr5b)//[2, 3, 4]
7、迭代方法
every()对数组中的每一项运行给定函数, 全true为true
some() 对数组中的每一项运行给定函数,有true即true
filter() 对数组中的每一项运行给定函数,返回true的项组成的数组
map()对数组中的每一项运行给定函数,返回函数调用返回的数组
forEach() 对数组中的每一项运行给定函数,无返回值