javascript - 如何在 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 条件?或者任何其他解决方案?
解决方案
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)
推荐阅读
- python - 如何将文件从 Django admin 直接上传到 Google Cloud Storage,以及如何在模板中呈现它们?
- python - 通过嵌套字典过滤
- ruby-on-rails - 从 API 访问嵌套 JSON 响应中的某些值
- node.js - 如何在同一个域上部署 2 个应用程序?
- kotlin - 是否可以使用 KType 作为泛型类型参数参数?
- php - 如何通过 id 获取主题的页码?
- amazon-web-services - 在 AWS 中担任角色时 RoleSessionName 的用例是什么以及它如何影响性能
- javascript - React 和 redux useEffect 对带有调度的异步函数
- xamarin - 如何替换 GTK 的 Xamarin.Forms 自定义渲染器中的 SearchBar 图标?
- r - 数据表操作的非等连接