【问题标题】:Add a new column in array with a value在数组中添加一个具有值的新列
【发布时间】:2021-08-11 12:10:33
【问题描述】:

我正在使用 API 检索某些股票的数据,我想添加一个名为 symbol 的列,其值为 query,但在 this.result.[i].push... 中出现错误 SyntaxError: Unexpected token '['。有没有其他方法可以调用第 i 个元素并传递查询数据,还是语法错误?

其余代码只是我将输出保存为 CSV 文件

这是代码:

import ObjectsToCsv from 'objects-to-csv';
import yahooFinance from 'yahoo-finance2';

async function api(){

  const query = 'TSLA';
  const queryOptions = { period1: '2021-08-06', interval: "1d"};
  let result = await yahooFinance.historical(query, queryOptions);

  function insertColumn() {
    for (var i = 0; i < this.result.length; i++) {
      this.result.[i].push({symbol: query}); // in this line I'm getting "SyntaxError: Unexpected token '['" in `this.result.[i].push...`
    }
  };

  console.log(result);

  (async () => {
    const csv = new ObjectsToCsv(result);
    await csv.toDisk('C:/Users/Rafael Oliveira/Desktop/teste/test.csv');
  })();
};
api();

提前感谢您,欢迎提供任何帮助(如果您有任何其他方法可以添加新列,例如 {symbol: query} 而不是我正在使用的列,请随时分享!}

【问题讨论】:

    标签: javascript arrays loops


    【解决方案1】:

    在数组索引之前不需要那个点。

    this.result.[i] // Bad
    this.result[i] // Good
    

    修复其他错误:

    import ObjectsToCsv from 'objects-to-csv';
    import yahooFinance from 'yahoo-finance2';
    
    async function api(){
    
      const query = 'TSLA';
      const queryOptions = { period1: '2021-08-06', interval: "1d"};
      let result = await yahooFinance.historical(query, queryOptions);
    
      const insertColumn = () => {
        for (var i = 0; i < result.length; i++) {
          result[i].push({symbol: query});
        }
      };
      insertColumn();
    
      console.log(result);
    
      (async () => {
        const csv = new ObjectsToCsv(result);
        await csv.toDisk('C:/Users/Rafael Oliveira/Desktop/teste/test.csv');
      })();
    };
    api();
    

    以这种方式声明insertColumn,您将在闭包中捕获result。另一种选择是将原始函数声明与this 绑定,并将结果变量声明为this.result 而不是let result

    this.result = await yahooFinance.historical(query, queryOptions);
    
      function insertColumn() {
        for (var i = 0; i < this.result.length; i++) {
          this.result[i].push({symbol: query});
        }
      };
     insertColumn.call(this)
    

    查看 MDN 了解更多信息:

    【讨论】:

    • 谢谢您,错误消除了,但该列仍未添加
    • 你不是在调用函数 insertColumn,你只是在声明 insertColumn。尝试调用它: insertColumn();
    • 当我调用函数 insertColumn 我得到TypeError: Cannot read property 'result' of undefined
    • 也感谢您提供资源!但是,我仍然收到相同的类型错误。在发布另一个查询之前,我会搜索一下答案,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2021-12-27
    • 2022-01-26
    • 2022-01-27
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多