简体   繁体   中英

with JavaScript i want to have the following output

Output an array where a value is added to the next value of the array. The Last value will be added with the first value.

Example: [45, 4, 9, 16, 25] Converted to: [49, 13, 25, 41, 70]

Map() method must be used.

您可以尝试以下操作:

 console.log([45, 4, 9, 16, 25].map((item, index, array) => item + array[(index + 1) % array.length]))

When using Array.prototype.map() you can use the index parameter and in each iteration
to see if it's the end of the array or not like so:

 const arr = [45, 4, 9, 16, 25]; const newArr = arr.map((item, i) => { return i !== (arr.length - 1) ? item + arr[i + 1] : item + arr[0]; }) console.log(newArr);

Array.prototype.map()

This works fine.

const nums = [45, 4, 9, 16, 25];

const newNums = nums.map((item, index) => {
  if(index < nums.length - 1) {
    return item + nums[ index + 1]
  }
    return item + nums[0]
})

console.log(newNums) // [ 49, 13, 25, 41, 70 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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