javascript - 不同对象内的矩阵的数学运算
问题描述
在 javascript 中,我有以下对象:
console.log(data)
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {species: "Citronela paniculata", cbh: Array(1)}
1: {species: "Myrcia splendens", cbh: Array(1)}
2: {species: "Araucaria angustifolia", plot: 1, cbh: Array(1)}
3: {species: "Bacharis montana", cbh: Array(1)}
4:
cbh: (2) [10, 20]
plot: 1
species: "Casearia decandra"
__proto__: Object
5: {cbh: Array(1), species: "Bacharis montana"}
6: {cbh: Array(3), species: "Ilex paraguariensis"}
7: {cbh: Array(1), species: "Ilex paraguariensis"}
8: {species: "Ilex paraguariensis", cbh: Array(1)}
9: {plot: 1, cbh: Array(1), species: "Araucaria angustifolia"}
length: 10
__proto__: Array(0)
我想将数组 cbh 的每个元素除以 pi,然后我使用:
let newData = data.map(({ plot, species, cbh }) => {
let dbh = cbh/Math.PI;
return { plot, species, cbh, dbh };
})
但是对于那些具有多个元素的数组,我得到了 NaN:
console.log(newData)
(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {plot: undefined, species: "Citronela paniculata", cbh: Array(1), dbh: 9.549296585513721}
1: {plot: undefined, species: "Myrcia splendens", cbh: Array(1), dbh: 10.185916357881302}
2: {plot: 1, species: "Araucaria angustifolia", cbh: Array(1), dbh: 5.729577951308232}
3: {plot: undefined, species: "Bacharis montana", cbh: Array(1), dbh: 4.7746482927568605}
4:
cbh: (2) [10, 20]
dbh: NaN
plot: 1
species: "Casearia decandra"
__proto__: Object
5: {plot: undefined, species: "Bacharis montana", cbh: Array(1), dbh: 6.366197723675814}
6: {plot: undefined, species: "Ilex paraguariensis", cbh: Array(3), dbh: NaN}
7: {plot: undefined, species: "Ilex paraguariensis", cbh: Array(1), dbh: 6.366197723675814}
8: {plot: undefined, species: "Ilex paraguariensis", cbh: Array(1), dbh: 15.915494309189533}
9: {plot: 1, species: "Araucaria angustifolia", cbh: Array(1), dbh: 15.915494309189533}
length: 10
__proto__: Array(0)
如何将cbh中的每个元素除以pi?任何提示都会很棒!先感谢您!
解决方案
将具有一个元素的数组除以 时Math.PI
,结果是一个数字。单元素数组隐式转换为数字,但元素数量多的数组无法转换为数字,所以得到NaN。无论如何,这种除法是行不通的,因为输出不会返回一个数组,而是一个数字或 NaN。
为了达到目标结果,您可以使用map 函数,它将源数组转换为新数组,对源数组的每个元素应用指定的转换(在这种情况下,除以Math.PI
):
let newData = data.map(({ plot, species, cbh }) => {
const dbh = cbh.map(value => value / Math.PI);
return { plot, species, cbh, dbh };
})
推荐阅读
- ios - 设置 UIProgressView.trackTintColor 时出现 CGPostError
- java - 有没有办法我可以只声明这些组一次?
- sdk - Rally 2.1 SDK 过滤器故事功能
- git - Gitlab 中的项目文件
- c# - MVC 访问静态文件
- android - 无法从不同的活动读取和写入数据到相同的共享首选项
- matlab - Matlab:找到下一个较小的浮点数
- sql-server - T-SQL - 重叠日期时间列的时间跨度
- c# - 使用他们的电子邮件地址 EWS 查找用户邮箱 GUID
- android - 如何将空白图标空间添加到preferencefragment