近期小伙伴儿们问了我很多后端返回的数据处理方式,我也给大家解决了两个,其实归根结底还是不熟悉关于数组的一些方法,其实前端尤其是主要做中后台开发的朋友,平常做的最多的除了跟antd或者其他ui框架打交道,就是处理各种后端返回来的数据了,那我今天就把咱们开发中常用的数组方法给大家做个汇总,希望能帮到你们。
1,push,pop,unshift,shift
作用:依次是 尾部添加,尾部删除,头部添加,头部删除
let arr=["张三","李四"]
arr.push("王五")
console.log(arr) // ['张三', '李四', '王五']
arr.pop()
console.log(arr) //["张三","李四"]
arr.unshift("刘备")
console.log(arr) //['刘备', '张三', '李四']
arr.shift()
console.log(arr) //['张三', '李四']
2,map
形式:array.map(function(item, index, arr), thisIndex)、
参数说明:
(1)参数必须是一个函数,数组中的每个元素都会执行这个函数。
(2)thisValue:可选,
对象作为该执行回调时使用,传递给函数,用作"this
"的值其中函数参数(很少用到)
(3)item:必选,代表当前元素
(4)index:可选,代表当前元素的索引,(如果仅是用来作为展示,可以作为key值)
(5)arr:可选,代表前元素属于的数组对象。(很少用到)
以下参数说明相同的情况就不过多赘述了
作用:它返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。
const data=[
{id:"001",number:1},
{id:"002",number:2},
{id:"003",number:3},
{id:"004",number:4},
]
const arr=data.map((item,index)=>{
item.number+=10
return item
})
console.log("arr",arr