【问题标题】:Sequentially splice values in array顺序拼接数组中的值
【发布时间】:2020-07-31 00:14:24
【问题描述】:

我正在尝试在 google.visualization.LineChart 中添加 data.addRows() 位置,该位置需要在一个数组中包含 2 个值的多个数组,其中第一个值需要为 0 到 127:

      /data.addRows([
        [0, 0], [100, 100]
        ]);

结果为一行:

通过创建多个点,我通过生成 128 个样本来使用沿路径函数的 google 海拔高度:

        elevator.getElevationAlongPath({
          'path': path,
          'samples': 128
        }, plotElevation);
      }

我创建了 var samples = Array.apply(null, {length: 128}).map(function(value, index){return index + 1;}); 我需要在一个数组中的多个数组中拼接从海拔[].elevation 获得的每个值。示例:

data.addRows([[0,48],
              [1,59],
              [2,67],
              [3,84],
              [4,122],
              [to 127, values]
              ]);

我尝试了 for 循环和嵌套 for 循环,但最终导致我的浏览器崩溃。

   for (var i = 0; i < elevations.length; i++) {
     samples.splice(1, 0, elevations[i].elevation);
      console.log(samples);
    }

如果我能做这样的事情,但它不起作用,那会很酷。

   for (var i = 0; i < elevations.length; i++) {
     samples[i].splice(1, 0, elevations[i].elevation);
      console.log(samples);
    }

全部简化: 我有:

var myArray1 = [{foo: bla, bar: blabla, foobar: 111,},  //
               {foo: bla, bar: blabla, foobar: 211,},  //  128 array's of foobar values.
               ----->                                    //
               {foo: bla, bar: blabla, foobar: 999,}];  //

1) 需要创建 1 个数组,其中包含 128 个数组。数组 0 中的第一个值需要从 0 开始,最后一个数组中的最后一个值需要在 127 结束:

var myArray2 = [[0],  //first array with first value of 0
                [1],  //second array with first value of 1
                -----> 
                [127]];

2) 需要循环将 myArray1[0 - 127].foobar 拼接到 myArray2 的第二个值中。最终结果需要如下所示:

var myArray2 = [[0, 111],
                [1, 211],
                -----> 
                [127, 999]];

【问题讨论】:

  • 返回一个数组[index, &lt;value&gt;],而不是返回一个数字(index + 1)。还是我错过了什么?
  • 什么是elevationssamples 是什么? -> 添加一个minimal reproducible example,显示(部分)输入和预期输出。

标签: javascript arrays splice


【解决方案1】:
const myArray1 = [[{foo: 'bla', bar: 'blabla', foobar: 111}],
                 [{foo: 'bla', bar: 'blabla', foobar: 211}],
                 [{foo: 'bla', bar: 'blabla', foobar: 999}]]

const myArray2 = myArray1.map((it, id) => [id, it[0].foobar])

display.log(JSON.stringify(myArray2)) // [[0,111],[1,211],[2,999]]

myArray1 的格式指定不正确。如果 [[{}], [{}], [{}], .... [{}]] 那么解决方案在顶部

【讨论】:

  • myArray1 错误已更正。 const myArray2 = myArray1.map((it, id) => [id, it[0].foobar]) console.log(myArray2); // 未捕获的类型错误:无法读取未定义的属性“myArray2”
  • ReferenceError: display is not defined
  • 那么... const myArray2 = myArray1.map((it, id) => [id, it.foobar])
猜你喜欢
  • 1970-01-01
  • 2018-04-30
  • 2018-09-09
  • 2012-03-25
  • 1970-01-01
  • 2018-08-26
  • 2015-01-31
  • 1970-01-01
  • 2013-02-13
相关资源
最近更新 更多