首页 > 解决方案 > 不同对象内的矩阵的数学运算

问题描述

在 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?任何提示都会很棒!先感谢您!

标签: javascriptarrays

解决方案


将具有一个元素的数组除以 时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 };
})

推荐阅读