简体   繁体   English

在添加元素时循环遍历数组中所有元素的最有效方法

[英]Most efficient way to loop through all elements in array while adding elements

I have a 2d array in Google Apps Script Javascript.我在 Google Apps 脚本 Javascript 中有一个二维数组。 I'm trying to loop through all elements but one of the loop options is adding another element.我正在尝试遍历所有元素,但其中一个循环选项是添加另一个元素。 So for example:例如:

for (let i in arr){
  if (arr[i][0] == "good")
    arr[i].push("clear");
  else if (arr[i][0] == "add")
    arr.splice(+i+1,0,"good");
}

But then it's not going through the actual end of the code, I presume because "let i in arr" is getting the leght of the array once and going to that end.但是它并没有经历代码的实际结尾,我想是因为“让 i in arr”一次获得了数组的长度并到达了那个结尾。 This is causing later issues.这导致了以后的问题。 Should I use a while or do while loop instead?我应该使用 while 还是执行 while 循环? Should I declare a length value and increase it manually whenever an element gets added?我是否应该声明一个长度值并在添加元素时手动增加它?

Use arr.length in your condition and it will check against the most up-to-date array length.在您的条件下使用arr.length ,它将检查最新的数组长度。

for (let i = 0; i < arr.length; i++) {
  if (arr[i][0] == "good")
    arr[i].push("clear");
  else if (arr[i][0] == "add")
    arr.splice(+i+1,0,"good");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM