在Array.reduce中使用对象解构

时间:2018-06-15 09:50:51

标签: javascript ecmascript-6 ecmascript-harmony

我试图使用Array.prototype.reduce...object解构在SO上解决另一个人的问题。我不明白为什么当我使用Object.assign时它按预期工作,但在使用扩展运算符时则不然。

const str = 'Jack:13,Phil:15,Lucy:12'

const arr = str.split(',')

let reducer = (acc, val) => {
  return { ...acc,
    ...{
      [val.split(':')[0]]: Number(val.split(':')[1])
    }
  }
}

let reducer2 = (acc, val) => {
  return Object.assign(acc, {
    [val.split(':')[0]]: Number(val.split(':')[1])
  })
}

let obj = {
  Jody: 29
}

let obj2 = {
  Julie: 28
}

arr.reduce(reducer, obj)
arr.reduce(reducer2, obj2)

console.log(obj)
/* output:
{
  "Jody": 29
}
*/
console.log(obj2)
/* output:
{
  "Julie": 28,
  "Jack": 13,
  "Phil": 15,
  "Lucy": 12
}
*/

1 个答案:

答案 0 :(得分:1)

数组reduce通常用于返回新值。即使它改变了累加器,也可以假设它可以返回一个新值。

arr.reduce(reducer, obj)依赖于obj发生变异。 reducer2确实改变了原始对象,这就是它起作用的原因。但这与reducer相矛盾,obj = arr.reduce(reducer, obj); 使累加器保持不变。

应该是:

reg_sort <- function(x,...,verbose=F) {
    ellipsis <-   sapply(as.list(substitute(list(...)))[-1], deparse, simplify="array")
    reg_list <-   paste0(ellipsis, collapse=',')
    reg_list %<>% strsplit(",") %>% unlist %>% gsub("\\\\","\\",.,fixed=T)
    pattern  <-   reg_list %>% map_chr(~sub("^-\\\"","",.) %>% sub("\\\"$","",.) %>% sub("^\\\"","",.) %>% trimws)
    descInd  <-   reg_list %>% map_lgl(~grepl("^-\\\"",.)%>%as.logical)

    reg_extr <-   pattern %>% map(~str_extract(x,.)) %>% c(.,list(x)) %>% as.data.table
    reg_extr[] %<>% lapply(., function(x) type.convert(as.character(x), as.is = TRUE))

    map(rev(seq_along(pattern)),~{reg_extr<<-reg_extr[order(reg_extr[[.]],decreasing = descInd[.])]})

    if(verbose) { tmp<-lapply(reg_extr[,.SD,.SDcols=seq_along(pattern)],unique);names(tmp)<-pattern;tmp %>% print }

    return(reg_extr[[ncol(reg_extr)]])
}