以下以test=[1,2,3,4,5]为例
1. slice方法--slice截取数组,不改变原数组
test.slice(1,2)=>[2]// 从下标1截取到下标2的前一个元素 test.slice(1)=>[2,3,4,5]//从下标1开始往后截取到末尾 test=>[1,2,3,4,5]2.splice方法--截取或拼接数组,改变原数组
test.splice(1,2)=>[2,3]//从下标1开始截取2个元素 test.splice(1)=>[2,3,4,5]//从下标1开始往后截取到末尾 test=>[1,4,5] test.splice(1,1,a,b,c)=>[1]//从下标1开始截取1个元素,并把a\b\c拼接到原位置 test=>[1,a,b,c,5]3.map方法--数组内部批量操作各元素,不改变原数组
test.map(function(x){ return x+10; });=>[11,12,13,14,15]//所有元素加10 test=>[1,2,3,4,5]4.filter方法--数组内部过滤元素,不改变原数组
test.filter(function(item,index){ return index%2==0; });=>[1,3,5]//获取下标为偶数的元素 test=>[1,2,3,4,5]5.every方法--判断数组每个元素是否满足条件,返回boolean值,不改变原数组
test.every(function(x){ return x<10; })=>true//判断数组内是否每个元素都小于10 test=>[1,2,3,4,5]6.some方法--判断数组是否含有某个元素满足条件,返回boolean值,不改变原数组
test.some(function(x){ return x>10; })=>false//判断数组内时候有值大于10 test=>[1,2,3,4,5]7.reduce方法--数组内各元素两两操作,不改变原数组
test.reduce(function(x,y){ return x+y; })=>15//各元素两两相加,获取每个元素相加之和 test.reduce(function(x,y){ return x>y?x:y; })=>5//各元素两两比较,获取最大值 test=>[1,2,3,4,5]8.isArray方法--判断对象是否为数组对象,只能由Array调用,被判断对象为参数
Array.isArray(test)=>true;9.jion方法--将数组各元素拼接为字符串,默认以,号链接,不改变原数组
test.jion()=>"1,2,3,4,5"//默认以逗号连接 test.jion("-")=>"1-2-3-4-5"//以-连接各元素 test=>[1,2,3,4,5]10.reverse方法--将数组倒序排列,改变元素组
test.reverse()=>[5,4,3,2,1] test=>[5,4,3,2,1]11.sort方法--将数组排序,默认以哈希值升序排列,改变原数组
test.sort()=>[1,2,3,4,5]//注意此排序并非以大小来排列 a=[11,5,32,2] test.sort()=>[11,2,32,5] a=[11,2,32,5] //sort方法可传入函数,作为其比较规则 test.sort(function(a,b){ return a-b; })=>[1,2,3,4,5]//按升序排列 test.sort(function(a,b){ return b-a; })=>[5,4,3,2,1]//按降序排列 test2=[{“name”:"小明","age":20},{“name”:"小花","age":17},{“name”:"小张","age":30}] test2.sort(function(a,b){ return a.age-b.age })=>[{“name”:"小花","age":17},{“name”:"小明","age":20},{“name”:"小张","age":30}] //将数组按对象的年龄进行升序排列12.concat方法--拼接数组,不改变原数组
test.concat([5,6])=>[1,2,3,4,5,5,6]//与数组拼接 test.concat(7,8)=>[1,2,3,4,5,7,8]//与元素拼接 test.concat([5,6],7,8)=>[1,2,3,4,5,5,6,7,8]//与数组和元素拼接 test.concat([[5,6],7,8])=>[1,2,3,4,5,[5,6],7,8]//注意喽,数组内部的数组将被视为整个元素啦 test=>[1,2,3,4,5]