首页 > 解决方案 > 如何在 if 条件下使用 reduce

问题描述

我有一个具有某些值的数组,我正在用它进行一些计算。

这是我的数组检查结果:

var arr2 = [1,2,2,3]

var newArr = [["a",0,1,2,0,223],["b",1,0,0,0,0],["c",0,0,0,0,223],["d",0,1,2,0,223]]

const result = newArr.reduce((results, element, index) => {
  return [
    ...results, // push the rest of the results onto the new array
    [
      ...element, // keep all the current items of the element (the 1d array)
      Math.round(element[element.length-1]-(element[element.length-1]/(element[element.length-3]+element[element.length-4])*arr2[index])) // add new element, by querying the last element of the array and the appropriate index of the second array
    ]
  ]
},[]);

console.log(result)

它工作正常,直到我的除数变为 0。在上面的代码中,(element[element.length-3]+element[element.length-4])有时结果为 0,它在数组中给出 NaN 或无穷大,我不希望它可以抛出零。

有没有一种方法可以在其中使用 if 条件?或者任何其他解决方案?

标签: javascriptarrays

解决方案


var arr2 = [1,2,2,3]

var newArr = [["a",0,1,2,0,223],["b",1,0,0,0,0],["c",0,0,0,0,223],["d",0,1,2,0,223]]

const result = newArr.reduce((results, element, index) => {
  const aValue = element[element.length-1]
  const bValue = element[element.length-3] + element[element.length-4]
  const value = aValue != 0 && bValue != 0 ? aValue/bValue : 0
  return [
    ...results, // push the rest of the results onto the new array
    [
      ...element, // keep all the current items of the element (the 1d array)
      Math.round(element[element.length-1]-(value*arr2[index]))
    ]
  ]
},[]);

console.log(result)


推荐阅读