split():拆分字符串变成数组(对字符串操作)join() :合并数组变成字符串(对数组操作)concat():连接两数组splice(begin,deleteCount,insert):拼接splic(begin,end):截取[begin,end)sort(callball(value1,value2)):排序resever():反序filter(callback(currentValue,index)):筛选map(callback(currentValue,index)):遍历,有返回值,和forEach类似forEach(callback(currentValue,index)):遍历,没有返回值reduce(callback(array,currentValue,index)[,array]):累计处理arguments:在函数内部使用,将函数的参数变成伪数组(不能用数组的 api)
sort排序:如果value1 < value2返回-1,升序排列;返回1,降序排列var arr = [1,5,4,3,2,6,7]
arr.sort((value1,value2) => {
if(value1 < value2){
return -1 //升序
}else if(value1 > value2){
return 1 //降序
}else{
return 0
}
})filter筛选数组,接受一个回调函数,回调函数的参数value、index(可选)、array(可选)let arr = [1,2,3,4,5,6,7,8,9]
arr.filter((value,index) =>{
console.log(index)
return value > 5 //筛选条件
})let fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
function find(element){
return fruits.filter((e)=>{
return e.indexOf(element) >= -1 //indexOf查到元素,找到返回元素的索引
})
}
find('ap') //['apple','grapes']map和forEach之间的区别是:map有返回值,forEach没有返回值;要forEach能返回值出来,在它内部定义一个变量存储遍历的值就可以了。var a = [1,2,3,4] a.map(e => e*2) //[1,4,6,8] a.forEach(e => e*2) //undefined, return 也不会出来
reduce接受两个参数,回调函数和回调函数的第一个参数(可选);回调函数接受四个参数:1、回调函数的返回值(处理结果)或者reduce的第二个参数;2、正在处理的元素;3、正在处理元素的索引;4、调用reduce的数组。如果reduce接收第二个参数,那么回调函数的第一个参数就是它(如去重,运行逻辑是把待处理数组的每一项处理后在一个个push进去,是加的过程);如果没有第二个参数,那么回调函数的第一个参数就是待处理数组的第一项(如摧毁数组,运行逻辑是把待处理数组直接拿过来集中处理,是减的过程)。
//去重:把待处理数组的每一项处理后在一个个`push`进去,是加的过程
var a = [1,2,3,2,4,5,3,1]
a.sort().reduce((arr,currentValue) => {
if(arr.length === 0 || arr[arr.length-1] !== currentValue){
arr.push(currentValue)
}
return arr
},[]) //[1,2,3,4,5]
//摧毁数组:把待处理数组直接拿过来集中处理,是减的过程
function destroyer(arr) {
return [].slice.call(arguments).reduce((current,next) =>{
return current.filter((e) => {
return e !== next
})
})
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3); //[1,1]arguments虽然不是数组,但可以将它转变成真正的数组,下面是两种方法function array(arr){
console.log(arr) //[1,2,3,4,5],注意是一个伪数组,不能用数组的方法
}
array(1,2,3,4,5)
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);下载本文