您的位置:首页 > 其它

ES5 Array新增方法

2017-04-07 11:25 603 查看
ES5数组新增了几个方法,已经不是什么新鲜事,我也已经用过几个,用起来非常方便,会帮我们解决很多逻辑复杂的问题。但是不常用就会忘,所以这里记录一下。方便自己查看。

回调函数的参数 1 当前遍历的对象本身item 2当前遍历的对象的下标index 3 遍历的数组本身 array

var names=["alice","lucy","divide","kate"];
//forEach  遍历循环
names.forEach(function (item,index,array) {
console.log(item+"   "+index)
})
//map   映射  将数组映射成新数组
var fullNames=names.map(function (item,index,array) {
return item+" green";
})
console.log(fullNames)
//filter 过滤  返回值是boolean true则通过 false则被抛弃
var filterNames=names.filter(function (item,index,array) {
return index
})
console.log(filterNames)
//some 指某些项合乎条件,与every相对
var scores=[56,66,78,98];
var score=60;
if(scores.every(function (item,index,array) {
return item>score;
})){
alert("都及格了")
}
if(!scores.every(function (item,index,array) {
return item>score;
})&&scores.some(function (item,index,array) {
return item>score
})){
alert("部分及格了")
}
//indexOf 字符串中indexOf自古就有,数组的indexOf与字符串类似 ,返回参数在数组中的下标(严格匹配 ===) 没有时返回-1  与lastIndexOf相对
var datas=[1,2,3,4,5]
console.log(datas.indexOf("1"))//-1
console.log(datas.indexOf(1))//0
console.log(datas.indexOf(2,1))//从下标为1的开始查找
//reduce 迭代 递归   reduceRight从右往左递归
var i=0
var sum=datas.reduce(function (previous,current,index,array) {
i=i+1;
return previous+current
},0)
console.log(i)slice&splice(这不是新增,但这俩方法我总是记忆混淆,也在此记录一下)
slice 英文释义:切片,菜刀。顾名思义就是切割数组的意思,返回一个切割后的新数组
原数组不变
var array=[1,2,3,4,5,6,7,8]
var newArray=array.slice(2,4)//切割从下标为2的开始到下标为4的结束,不包含最末一个。并组成新数组返回
console.log(newArray)//[3,4]
splice 英文释义:结合,拼接 所以splice的用法是可以删除可以新增
splice(index,count,new1,new2,new3....,newX)
splice()方法可删除从index处开始的count个元素,然后紧接着添加新的new1 new2 new3等
新元素。splice是改变数组本身,返回的是删除的数据组成的数组

 
var newArray2=array.splice(0,3,"a","b","c")//从0开始删除3个元素,并插入a,b,c
console.log(newArray2)//[1,2,3]
console.log(array)//["a","b","c",4,5,6,7,8]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: