【问题标题】:how to create dynamic array with x y coordinates in react native如何在本机反应中创建具有x y坐标的动态数组
【发布时间】:2018-05-25 10:53:13
【问题描述】:

朋友们好,我想借助 JSON 数组值创建 x-y 坐标的动态数组,因此低于 JSON 值

"data": [
  {
    "x_value": 1,
    "y_value": 1527116400
  },
  {
    "x_value": 43.45,
    "y_value": 1527030000
  },
  {
    "x_value": 43.95,
    "y_value": 1526943600
  },
  {
    "x_value": 43.95,
    "y_value": 1526857200
  },
  {
    "x_value": 44.05,
    "y_value": 1526598000
  },
  {
    "x_value": 44.25,
    "y_value": 1526511600
  },
  {
    "price": 44.1,
    "y_value": 1526425200
  },
  {
    "x_value": 44.3,
    "y_value": 1526338800
  },
  {
    "x_value": 44.25,
    "y_value": 1526252400
  }

]

我的Js代码如下

var data = null;
var array_data = response.sData.chart_data;
for (let index = 0; index < chart_data.length; index++) {
    data.push({ array_data[index].x_value, y: chart_data[index].y_value });
}

当我运行上面的代码时,我会收到类似的错误消息;

TypeError: null 不是一个对象(评估'data.push')

知道如何解决这个问题吗?您的所有建议都很有价值。

【问题讨论】:

  • var data =[] :|
  • 你不能在布尔变量上使用Array.prototype.push()

标签: javascript arrays loops react-native


【解决方案1】:

在您的代码中,您不能在布尔值 var data = null; 变量上使用 Array.prototype.push()

最好使用Array.prototype.map(),它会创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

代码示例:

const chart_data = [{"x_value": 1,"y_value": 1527116400},{"x_value": 43.45,"y_value": 1527030000},{"x_value": 43.95,"y_value": 1526943600},{"x_value": 43.95,"y_value": 1526857200},{"x_value": 44.05,"y_value": 1526598000},{"x_value": 44.25,"y_value": 1526511600},{"price": 44.1,"y_value": 1526425200},{"x_value": 44.3,"y_value": 1526338800},{"x_value": 44.25,"y_value": 1526252400}];
const data = chart_data.map(coordinate => ({
  x: coordinate.x_value,
  y: coordinate.y_value
}));

console.log(data);

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2023-04-01
    • 1970-01-01
    • 2023-02-17
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多