数组常见的方法(增删改查)
下面将数组的方法分为5类(官方文档中可查)
- 给数组添加元素(增):push(), unshift(),splice()
- 从数组中删除元素(删):pop(), shift(),splice()
- 修改数组中的元素(改):splice(),reverse(),sort()
- 从已有数组中返回选定的数组(查):slice()
- 用于遍历的函数:forEach(),map(),filter()
- 不会改变元素数组的内容的函数:concat(),slice(),map(),filter()
forEach
//如果出入的数组中的值不是对象,则以下操作无法改变数组的值 function checkFor(arr) { arr.forEach((item,index)=>{ //若传入的不是对象,要想改变数组中的item值,可直接用arr[index] = '新数据' item["name"]='000' item["look"] = 'pretty' }) return arr }
示例
console.log(checkFor([1,2,3,4]));//[1,2,3,4] console.log(checkFor(['www','ooo']));//['www','ooo'] console.log(checkFor([{name:'cql'},{age:18}]));//[{name: "000", look: "pretty"},{age: 18, name: "000", look: "pretty"}]