【问题标题】:Array overwrite issues in Google ScriptsGoogle Scripts 中的数组覆盖问题
【发布时间】:2015-02-25 20:51:48
【问题描述】:

我正在编写一个谷歌表格扩展。基本上,该脚本会查看如下表格: “一个” | "B" | "C" | "E~F"

对于第四列中由“~”分割的每个字符串,我需要创建两个数组,以便最后一列是 E 或 F,但其余值相同,如下所示: [["A","B","C","E"],["A","B","C","F"]] 现在,理论上这应该很容易:我拆分最后一列并循环遍历它。但是,当我附加我的数组时,它会覆盖第二个值,给我留下: [["A","B","C","F"],["A","B","C","F"]]。 请注意,E 列将来会有不确定数量的元素。 感谢您的帮助!

    var rangeArr=[["BF-A", "true", 'A kind reminder to make a weather report if you are on duty today', 'Something','2.0', 'Humphrey Bogart~James Dean'], ['BF-B', 'true', 'Kindly report on the condition of the BF now', 'Something else', '4.0', 'Humphrey Bogart~James Dean'], ['R-A6', 'true','A kind reminder to report on the reservoir level', 'Something completely different', '1.0', 'Angela Merkel']];
      var newArr=[[]];

      var count=0;
      for(i in rangeArr){
        var str=rangeArr[i][5];
        var places=str.split("~");
        var otherThings=rangeArr[i];
        otherThings.pop()
        for (a in places){
         otherThings[5]=places[a]
         var nextThing=otherThings
         newArr[count]=nextThing;
         count=count+1;
          
          }
        }
    alert(newArr)
    

【问题讨论】:

  • 从 E 列中拆分出的元素是否会超过两个?
  • 是的。很抱歉之前没有提到,不幸的是 E 列中的元素数量是不确定的,并且会变得非常大。
  • 我认为问题在于newArr[count] 实际上被填充了对otherThings引用,每次迭代都会对其进行更新。一个解决方案是使用var nextThing = otherThings.slice()

标签: javascript google-apps-script google-api google-sheets


【解决方案1】:

我找到了解决方法。我完全不明白为什么前面的代码不起作用,这可能反映了我对 JS 数组缺乏了解。我只是从两个不同数组的元素中创建了一个数组,而不是在原始数组中添加一个元素。

var rangeArr=[["BF-A", "true", 'A kind reminder to make a weather report if you are on duty today', 'Something','2.0', 'Humphrey Bogart~James Dean'], ['BF-B', 'true', 'Kindly report on the condition of the BF now', 'Something else', '4.0', 'Humphrey Bogart~James Dean'], ['R-A6', 'true','A kind reminder to report on the reservoir level', 'Something completely different', '1.0', 'Angela Merkel']];
  var newArr=[[]];

  var count=0;
  for(i=0; i<rangeArr.length; i++){
    var str=rangeArr[i][5];
    var places=str.split("~");
    var otherThings=rangeArr[i]; 
    otherThings.pop()
    for (a=0; a<places.length; a++){
      newArr[newArr.length]=[otherThings[1],otherThings[2],otherThings[3],otherThings[4],places[a]]
      count=count+1;
        
      }
  }

  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多