简体   繁体   English

在同一 map (JavaScript) 中引用 map 值

[英]reference map value in the same map (JavaScript)

I am certain my issue here is not knowing what to call what I'm trying to do here, so any help with that would be appreciated, but I'd like to map over an array and create two values, where the first one refers to the prior value... is that possible?我确定我在这里的问题是不知道该怎么称呼我在这里尝试做的事情,所以任何帮助都将不胜感激,但我想通过数组 map 并创建两个值,第一个是指到先前的价值……这可能吗?

arr =[1,2,3]
arr.map((el, i) => ({ 
   x: el, 
   y: 5, 
   z: y[i] + 2 // is there a way I can write this so I can refer to y ???
}))

any help appreciated!任何帮助表示赞赏!

Is this what you're looking for?这是你要找的吗?

const arr = [1, 2, 3]

const newArr = arr.map((currentValue, currentIndex) => {
  const previousValue = currentIndex > 0 ? arr[currentIndex - 1] : 0

  const output = {
    x: currentValue,
    y: 5,
    z: previousValue + 2
  }

  return output
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM