GVKun编程网logo

Js的reduce()方法(js的reduce方法)

9

此处将为大家介绍关于Js的reduce()方法的详细内容,并且为您解答有关js的reduce方法的相关问题,此外,我们还将为您介绍关于es6中reduce()方法和reduceRight()方法、ES

此处将为大家介绍关于Js的reduce()方法的详细内容,并且为您解答有关js的reduce方法的相关问题,此外,我们还将为您介绍关于es6 中 reduce () 方法和 reduceRight () 方法、ES6中的reduce、javascript – Redux combineReducers没有将状态传递给reducer、javascript – 从redux中的reducer中获取ID的有用信息。

本文目录一览:

Js的reduce()方法(js的reduce方法)

Js的reduce()方法(js的reduce方法)

Js 数组reduce()方法应用一个函数针对数组的两个值(从左到右),以减至一个值。
语法:array.reduce(callback[, initialValue])
参数说明:
1)callback是调用方法;
2)initialValue是callback初次调用时的第一个参数值。

示例1--数组求和:

[1,2,3,4,5].reduce((prev,next)=>{
        return prev+next;
    })//返回值15

示例2--对象求和:

var ps = [{''p'':1,''num'':1},{''p'':2,''num'':2},{''p'':3,''num'':3},{''p'':4,''num'':4}];
    ps.reduce((prev,next)=>{
        return prev+next.p*next.num;
    },0)//回调函数的第一次调用时,第一个参数是0,第二个参数是ps[0]

 示例3

let titles= titles:[
          {
            title:"你的",
            content:"你的东西",
            url:"https://www.baidu.com",
            completed:false
          },
          {
            title:"我的",
            content:"我的东西",
            url:"http://www.youku.com",
            completed:true
          },
          {
            title:"他的",
            content:"他的东西",
            url:"http://sjzx.niha.org.cn",
            completed:true
          }
        ]

 let completeSize = this.titles.reduce((preTotal, title) => preTotal + (title.completed?1:0) ,0)

 

es6 中 reduce () 方法和 reduceRight () 方法

es6 中 reduce () 方法和 reduceRight () 方法

es6 中 reduce () 方法
从左往右开始

参数:
prev:它是上一次调用回调时返回的结果,每次调用的结果都会给 prev

cur:当前的元素

index:当前的索引

arr:循环的数组

返回值:
函数累计处理的结果

demo:
求数组的和。

var a = [1,2,3,4,5,6,7,8,9,10]

var str = a.reduce(function(prev,cur,index,arr){
return prev + cur ;
})
str // 55;

 


求阶乘

var a = [1,2,3,4,5,6,7,8,9,10]

var str = a.reduce(function(prev,cur,index,arr){
return prev * cur ;
})

str //3628800

 


求幂

新增的一个运算符 

A ** B;

var a = [2,3,4];

var str = a.reduce(function(prev,cur,index,arr){
return prev ** cur ;
})

str // 4096

 

 

将二维数组转换成一维


str //(10) [0,1, 2, 3, 4, 5, 6, 7, 8, 9]
 数组去重

var arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
var str = arr.sort().reduce((prev, cur)=>{
if(prev.length===0 || prev[prev.length-1]!==cur){
prev.push(cur);
}
return prev;
}, []);
str // (5) [1, 2, 3, 4, 5]

 

 

es6 中 reduceRight () 方法
从右往左开始

参数和上面是一样。

结果都是一样的我就不写代码了

 

ES6中的reduce

ES6中的reduce

let arr1 = [0, 1, 2, 3, 4].reduce(function (accumulator, currentValue, currentIndex, array) {
        // accumulator 累计器
        // currentValue 当前值
        // currentIndex 当前索引
        // array 数组
        return accumulator + currentValue
      })
      // 等价于
      let arr2 = [0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr)
      console.log(arr2)

      // 提供一个初始值作为reduce()方法的第二个参数
      let arr3 = [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
        return accumulator + currentValue
      }, 10)
      console.log(arr3)

      // 要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数
      let initialValue = 0
      let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
        return accumulator + currentValue.x
      }, initialValue)
      console.log(sum) //  6

      // 将二维数组转化为一维
      let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
        function (a, b) {
          return a.concat(b)
        },
        []
      )
      console.log(flattened)// [0, 1, 2, 3, 4, 5]

      // 计算数组中每个元素出现的次数
      let names = [''Alice'', ''Bob'', ''Tiff'', ''Bruce'', ''Alice'']
      let countedNames = names.reduce(function (allNames, name) {
        if (name in allNames) {
          allNames[name]++
        } else {
          allNames[name] = 1
        }
        return allNames
      }, {})
      console.log(countedNames)

      // 按属性对object分类
      let people = [
        {name: ''Alice'', age: 21},
        {name: ''Max'', age: 20},
        {name: ''Jane'', age: 20}
      ]

      function groupBy(objectArray, property) {
        return objectArray.reduce(function (acc, obj) {
          var key = obj[property]
          if (!acc[key]) {
            acc[key] = []
          }
          acc[key].push(obj)
          return acc
        }, {})
      }

      let groupedPeople = groupBy(people, ''age'')
      console.log(groupedPeople)

      // 数组去重
      let myArray = [''a'', ''b'', ''a'', ''b'', ''c'', ''e'', ''e'', ''c'', ''d'', ''d'', ''d'', ''d'']
      let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
        if (accumulator.indexOf(currentValue) === -1) {
          accumulator.push(currentValue)
        }
        return accumulator
      }, [])

      console.log(myOrderedArray)

 

javascript – Redux combineReducers没有将状态传递给reducer

javascript – Redux combineReducers没有将状态传递给reducer

在以下代码中,combineReducers不会将数据(状态,操作)传递给reducer.它会在下面生成错误.可能只是我犯的一个小错误.链接到JSfiddle:https://jsfiddle.net/bengrunfeld/1h0t59uf/

import React from 'react'
import { render } from 'react-dom'
import { combineReducers } from 'redux'
import { Constants } from './constants/constants'


const goal = (state = 0,action) => {
  (action.type === Constants.ADD) ?
    state + action.payload:
    state
}

const target = (state = 0,action) => {
  (action.type === Constants.REMOVE)?
    state - action.payload:
    state
}

const reducer = combineReducers({
  goal,target
})

const state = 10

const newState = reducer(state,{
  type: Constants.REMOVE,payload: 5
})

render(
  

错误信息

main.bundle.js:28054 Uncaught Error: Reducer "goal" returned undefined during initialization. If the state passed to the reducer is undefined,you must explicitly return the initial state. The initial state may not be undefined.
    at http://localhost:3000/main.bundle.js:28054:13
    at Array.forEach (native)
    at assertReducerSanity (http://localhost:3000/main.bundle.js:28049:25)
    at combineReducers (http://localhost:3000/main.bundle.js:28104:5)
    at Object.
最佳答案
const Constants = {
  REMOVE: "REMOVE",ADD: "ADD"
}

const goal = (state = 5,action) => {
  return (action.type === Constants.ADD) ?
    state + action.payload:
    state
}

const target = (state = 5,action) => {
  return (action.type === Constants.REMOVE)?
    state - action.payload:
    state
}

const reducer = Redux.combineReducers({
  goal,target
})

const state = {goal: 10,target:5}

const newState = reducer(state,payload: 5
})

console.log(newState);

ReactDOM.render(
  

                  

总结

以上是小编为你收集整理的javascript – Redux combineReducers没有将状态传递给reducer全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

ecmascript-6

javascript – 从redux中的reducer中获取ID

javascript – 从redux中的reducer中获取ID

我很新,并尝试使用react& amp来构建一个简单的书签应用程序.终极版.

我无法解决这个问题:

用户可以创建一个书签并将其添加到多个文件夹.所以我发送一个addMark(书签)动作,然后发送addMark(文件夹)或editFolder(文件夹),如果该文件夹已存在.正如您所看到的,书签和文件夹是通过相同的操作添加的,因为在我的状态树中,它们都只是标记 – 由它们的类型属性区分.

我的问题:如何告诉文件夹对象哪个是新书签添加到书签的文件夹列表?如何在两个调度之间检索新创建的书签的ID?

解决方案我觉得不满意:

>我知道如何在reducer中生成书签ID(通过现有书签ID上的Math.max),因此我可以在2个调度之间重现新的书签ID.这听起来像是一个糟糕的黑客.
>书签和文件夹保存在同一个状态分支(相同的缩减器)中,因为它们都只是“标记”,我可以有一个引用最新添加的书签的状态属性,但这听起来也像是一个糟糕的黑客.

一点源代码,了解我所拥有的:

// mapping between dispatcher and props to my react view
const mapdispatchToProps = (dispatch) => ({
  saveMark: (mark) => {
    if (mark.id) {
      dispatch(editMark(mark));
    } else {
      dispatch(addMark(mark));
    }
  },});
export default connect(mapStatetoProps,mapdispatchToProps)(AddMark);

在AddMark中,它是容器组件:

// save the bookmark first
this.props.saveMark({
      type: 'bookmark',title: this.state.title,url: this.state.url,icon: this.props.icon,style: this.state.style,});
 // Now I need the bookmark ID
 folders.forEach(folder => {
    folder.children.push(bookmarkID) // <-- !!!
 });
 folders.forEach(folder => this.props.saveMark(folder));

我找不到令人满意的解决方案.

最佳答案
我认为你应该只在这里调度一个动作:addBookmark(),它接受书签对象和文件夹.

处理将书签对象添加到文件夹中的代码应该是reducer的一部分.

另外,请参阅Redux项目中的Todos example.它在动作创建中提供了id,使其可以在组件中读取它.您还可以使用当前状态来计算最新ID:

function addBookmark(bookmark,folder) {
   return (dispatch,getState) => {
       const newBookmark = Object.assign({
         id: Math.max(0,...getState().bookmarks.map(b => b.id)) + 1,},bookmark);
       dispatch({
         type: 'ADD_BOOKMARK',bookmark: newBookmark,folder: folder
       });
   }
}

请注意,该示例需要redux-thunk中间件来分派这些操作.

然后,您可以在文件夹reducer中访问带有id的书签

function folderReducer(state = [],action) {
  if(action.type === 'ADD_BOOKMARK') {
     return state.map(folder => {
       if(folder === action.folder) {
         return Object.assign({},folder,{children: [...folder.children,action.bookmark.id]}
       }
       return folder;
     })
  }
  //another reducer code
  return state;
} 

关于Js的reduce()方法js的reduce方法的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于es6 中 reduce () 方法和 reduceRight () 方法、ES6中的reduce、javascript – Redux combineReducers没有将状态传递给reducer、javascript – 从redux中的reducer中获取ID等相关知识的信息别忘了在本站进行查找喔。

本文标签: