繁体   English   中英

我正在尝试从对象数组中检索数字数组

[英]I am trying to retrieve an array of numbers from an array of object

当我运行generateData()函数时,它返回NaN数组。

function generateData(name) {
    var arr = [];
    var t;
    const x = name;
    for (i = 0; i < data.data.length; i++) {
        t = Number(data.data[i].x)
        arr.push(t);
    }
    return arr;
}

物体 -

{data: Array(15), errors: Array(1), meta: {…}}
data: Array(15)
0: {Node no.: 1, CenterA: 0, LeftA: 4.36, RightA: 3.86, RoadA: 1.14, …}
1: {Node no.: 2, CenterA: 5, LeftA: 1.71, RightA: 1.57, RoadA: 2.07, …}
2: {Node no.: 3, CenterA: 0, LeftA: 3.79, RightA: 4.79, RoadA: 2.86, …}
3: {Node no.: 4, CenterA: 4.64, LeftA: 5.36, RightA: 2.29, RoadA: 2.5, …}
4: {Node no.: 5, CenterA: 0, LeftA: 4.21, RightA: 4.43, RoadA: 2.14, …}
5: {Node no.: 6, CenterA: 4.86, LeftA: 3.21, RightA: 1.43, RoadA: 2.21, …}
6: {Node no.: 7, CenterA: 0, LeftA: 5.79, RightA: 5.5, RoadA: 2.36, …}
7: {Node no.: 8, CenterA: 5.86, LeftA: 2.71, RightA: 3.21, RoadA: 2.93, …}
8: {Node no.: 9, CenterA: 0, LeftA: 5.29, RightA: 6.64, RoadA: 2.64, …}
9: {Node no.: 10, CenterA: 5.57, LeftA: 1.36, RightA: 2.86, RoadA: 2.07, …}
10: {Node no.: 11, CenterA: 0, LeftA: 5.43, RightA: 5.29, RoadA: 1.5, …}
11: {Node no.: 12, CenterA: 4.43, LeftA: 2.79, RightA: 4.21, RoadA: 3.21, …}
12: {Node no.: 13, CenterA: 0, LeftA: 4.79, RightA: 5.43, RoadA: 2.29, …}
13: {Node no.: 14, CenterA: 0, LeftA: 4.57, RightA: 3.64, RoadA: 2.71, …}
14: {Node no.: null}

我需要一个包含不同列的所有条目(例如RightA,CenterA等)的数组。我在代码中使用了Number()函数将条目转换为数字,但仍然无法正常工作

使用计算的属性名称:

t = Number(data.data[i][x])
t = Number(data.data[i].x)

在这种情况下, data.data[i].x试图访问名为data.data[i] x的属性,该属性等效于data.data[i]['x']

您要访问变量x的值的属性,因此需要使用方括号表示法来访问计算出的属性名称:

t = Number(data.data[i][x])

否则,该值将是不确定的,除非data.data[i]具有属性x ,该属性x仍然会导致不良结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM