马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
操纵数组方法
记录一下自己常用到的操纵数组的方法
1.forEach()
遍历数组 在回调函数中对原数组的每个成员举行修改(不用 return)
方法吸收一个回调函数 回调函数吸收两个参数 第一个是遍历的当前元素 第二个是元素的索引
- const arr = [
- {
- name: '张三'
- },
- {
- name: '李四'
- },
- {
- name: '王五'
- }
- ]
- //遍历 arr 数组然后给每个对象元素中添加一个 id 属性 值为索引值
- arr.forEach((item, index) => {
- item.id = index
- })
- console.log(arr);
复制代码 2.reduce()
遍历数组中每个元素举行迭代操纵,累加、累乘之类(在回调中必要 return 每次迭代完成的值 为下一次迭代利用)
方法吸收两个参数 第一个是回调函数 第二个是迭代的初始值
回调中吸收两个参数 第一个是每次迭代完成的值 第二个是遍历的当前元素
- const arr = [
- {
- name: '张三',
- num: 1
- },
- {
- name: '李四',
- num: 2
- },
- {
- name: '王五',
- num: 3
- }
- ]
- //遍历 arr 数组根据每个对象元素中中的 num 属性 进行累加迭代
- const finaltotal = arr.reduce((total, item) => {
- return total + item.num
- }, 0)
- console.log(finaltotal);
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |