数组操作
forEach()
forEach我们很常用,它只是for循环的简单替代
arr.forEach((val,index,arr)=>{
console.log(val,index,arr)
})
map()
与forEach相似,做数据交互,映射机制
正常情况下,要配合return,若没有return相当于forEach
一般呢,我们用来重新整理数据结构,如果后台给我们的数据属性名称与我们前端的名称不同,我们就可以使用map
let arr = [
{name:"Peter",age:8,action:"computer_game"},
{name:"Sam",age:5,action:"sing"},
{name:"Timmmy",age:15,action:"basketball"},
{name:"Linda",age:22,action:"dance"},
]
let newArr = arr.map((item,index)=>{
let json = {
name:item.name,
age:item.age + 10,
words:`I Love ${item.action}`
}
return json
})
console.log(newArr)
filter()-----过滤
如果回调函数返回true,就会留下原数据
let newArr = arr.filter(item=>{
return item.age >10
})
console.log(newArr)
some()
类似查找,数组里面某一个元素符合条件,返回true
every()
数组里面所有的元素都要符合条件,返回true
reduce()
求数组和
let res = arr.reduce((prev,cur,index,arr)=>{
return prev + cur;
});
我们返回的值存为prev,cur是本次循环的值
ES6------for-of
for(let item of arr){}
//循环结果为下标
for(let index of arr.keys()){}
//循环结果为实体,下标加值,结果为数组
for(let item of arr.entries()){}
//我们也可以解构,这样返回的就是确切的值了
for(let [index,val] of arr.entries()){}
Array.from:
作用: 把类数组(获取一组元素、arguments...) 对象转成数组
个人观点: 具备 length这个东西,就靠谱
Array.of(): 把一组值,转成数组
let arr = Array.of('apple','banana','orange');
console.log(arr);