【发布时间】: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