在javascript中正确迭代数组的前n个元素

时间:2022-01-07 00:36:13

I have a trouble executing the following snippet. It is callback code for a larger python Bokeh plotting. Since my experience with javascript is limited I was drawing from this question on how to loop over an array in javascript.

我在执行以下代码段时遇到问题。它是更大的python Bokeh绘图的回调代码。由于我对javascript的经验有限,我正在从这个问题中得出如何在javascript中循环数组。

This is the modified objects2 = ColumnDataSource(data=dict(x=[],y1=[],y2=[],y3=[], y4=[]))

这是修改后的objects2 = ColumnDataSource(data = dict(x = [],y1 = [],y2 = [],y3 = [],y4 = []))

  var inds = cb_obj.get('selected')['1d'].indices; // Obtains column numbers
  var d1 = m1.get('data'); // Obtains matrix with numbered columns that correspond to inds
  var d2 = s2.get('data'); // Plotted data columns that get modified according to inds
  var ys = ['y1','y2','y3','y4']; // Array of names of columns in d2/s2
  var j, y, select= ys.slice(0,inds.length+1), // Limit number of columns to number of inds

  //This piece is from the linked question -  a loop through select (e.g only 'y1' and 'y2')
  var len = select.length;
  for(j=0; j<len; ++j) {
    if (j in select) {
      y = selected[j]; 
      // For each selected name of a column
      d2[y] = [];  // Erase current value
      // Fill the column from d1  (12 is just the length of the column)
      for (var i = 0; i < 12; i++) {
        d2[y].push(d1[inds[j]][i]),
      }
    }
  }
  s2.trigger('change');

The second loop was working just fine for a predefined number of y1,y2, when only two indices were passed to it. But my goal is to make the selection size dynamic i.e for a varying number of indices like [1,5,65,76] or [1,8] which is passed down from outside to inds, the code is to fill up appropriate number of ys so either y1,y2,y3,y4 or just y1,y2 with data from d1/m1.

当只有两个索引传递给它时,第二个循环对预定义数量的y1,y2工作得很好。但我的目标是使选择大小动态,即对于从[1,5,65,76]或[1,8]这样从外部传递到inds的不同数量的索引,代码是填充适当的数字ys,y1,y2,y3,y4或y1,y2,数据来自d1 / m1。

From what I can tell the code "should" be doing just that , but I am obviously not seeing something.

从我可以告诉代码“应该”正在这样做,但我显然没有看到一些东西。

For comparison here is the previous version of code that worked, but was limited to exactly two indices.

为了比较,这里是以前版本的代码,但仅限于两个索引。

  var inds = cb_obj.get('selected')['1d'].indices;
  var d1 = m1.get('data'); 
  var d2 = s2.get('data');
  d2['y'] = []
  d2['y2'] = []
  for (i = 0; i < 12; i++) {
    d2['y1'].push(d1[inds['0']][i]),
    d2['y2'].push(d1[inds['1']][i])
  }
  s2.trigger('change');

Here is the whole thing (Python) with sample data for better visualization.

以下是包含示例数据的整个事物(Python),以实现更好的可视化。

1 个解决方案

#1


0  

I figured it out. There was an extra comma at the end of this line

我想到了。在这一行的末尾有一个额外的逗号

d2[y].push(d1[inds[j]][i])

#1


0  

I figured it out. There was an extra comma at the end of this line

我想到了。在这一行的末尾有一个额外的逗号

d2[y].push(d1[inds[j]][i])