如何在JS /应用程序中将数组A的值分配给数组B?

时间:2019-03-03 06:26:18

标签: javascript appscript

我正在使用AppScript开发一些Stock工具,但是现在我不知道为什么不能将数组A的值分配给数组B。有人可以帮我吗?

我要复制values_array [l] [0]-> dataArray [l] [0]

能给我解决方法吗?

//Filled up the array for MACD 
// var dataArray = [["Stock","Date","Close Price","EMA12","EMA26","DIF","Signal"]];
var dataArray = [];
var accumulationEMA12 = 0;

for (var l = 0; l < values_array.length - 1; l++) // Get the previous day EMA12
{
  var temp = values_array[l][5];

  //  var accumulationEMA12 = accumulationEMA12 + values_array[l][5];

  var accumulationEMA12 = accumulationEMA12 + temp;

  dataArray[l][0] = values_array[l][0]; // Fill Up the Stock No. <-Here
  dataArray[l][1] = values_array[l][1]; // Fill UP the Date <-Here


  if (l < 11) //if the dataset is < 12 rows or < 26 rows, calculate the average instead of EMA
  {

  }
}

 //Filled up the array for MACD 
   // var dataArray = [["Stock","Date","Close Price","EMA12","EMA26","DIF","Signal"]];
    var dataArray = [];
    var accumulationEMA12 = 0;
    
    for(var l = 0; l< values_array.length-1; l++) // Get the previous day EMA12
    {  
      var temp = values_array[l][5];
   
    //  var accumulationEMA12 = accumulationEMA12 + values_array[l][5];
      
      var accumulationEMA12 = accumulationEMA12 + temp;

      dataArray[l][0] = values_array[l][0]; // Fill Up the Stock No.
      dataArray[l][1] = values_array[l][1]; // Fill UP the Date
      
          
      
      if(l < 11) //if the dataset is < 12 rows or < 26 rows, calculate the average instead of EMA
      {
       
      }
    }

此处为Values_array enter image description here

1 个答案:

答案 0 :(得分:0)

我认为您在电话中遇到错误

dataArray[l][0] = values_array[l][0];

因为,在我看到的任何地方,您都没有发起dataArray[l]。在您的代码中,dataArray[l]undefined,因此,当您尝试执行类似dataArray[l][1]之类的操作时,实际上是在进行undefined[1],这会引发此类错误

Uncaught TypeError: Cannot read property '1' of undefined

因此,您需要做的是确保dataArray[l]本身就是一个数组。像这样

var dataArray = [];
for (var l = 0; l < values_array.length; l++) {
  // make sure dataArray[l] exists
  dataArray[l] = [];

  // do your operations
  dataArray[l][0] = values_array[l][0];
  dataArray[l][1] = values_array[l][1];

  // other code.
}

尽管如此,我还是建议使用现代JS语言功能,例如

const dataArray = [];
values_array.forEach((val, index)=> {
  // notice that we are assigning a new array to dataArray[index] 
  dataArray[index] = [
    val[0],
    val[1],
  ];

  // do other operations like
  if (index < 11) {
    // do stuff
  }
});

希望有帮助。