在 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: 1species: "Casearia decandra"__proto__: Object5: {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: NaNplot: 1species: "Casearia decandra"__proto__: Object5: {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?任何提示都会很棒!先感谢您!
1 回答
慕容森
TA贡献1853条经验 获得超18个赞
将只有一个元素的数组除以 时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 };
})
添加回答
举报
0/150
提交
取消