简体   繁体   English

在 for 循环中使用 array.splice 时发生无限循环

[英]infinite loop occurs when using array.splice inside a for loop

I write this code, for inserting the second argument if any of the array items are bigger than it.我编写此代码,用于在任何数组项大于它时插入第二个参数。 but suddenly an infinite loop occurs.但突然出现无限循环。 ('result.splice(i, 0, num)' causes it) Can anybody tell me why?! ('result.splice(i, 0, num)' 导致它)有人能告诉我为什么吗?!

function getIndexToIns(arr, num) {
  let result = arr.sort(function(a, b){return a - b})
  for(let i = 1; i <= result.length ; i++){
    result.splice(i, 0, num)
  }
  return result;
}

getIndexToIns([40, 60, 20, 0], 50);

Your您的

result.splice(i, 0, num)

inserts a new value at the index and increments the length of the array.在索引处插入一个新值并增加数组的长度。

Beside that, you loop over the last given index, too.除此之外,您还可以遍历最后一个给定的索引。

Instead, you could sort and iterate from the end to replace grater values with the maximum wanted value.相反,您可以从末尾进行排序和迭代,以用最大想要的值替换更粗的值。

 function sortAndReplaceGreaterValues([...array], number) { array.sort((a, b) => a - b); let i = array.length; while (i--) { if (array[i] < number) break; array[i] = number; } return array; } console.log(sortAndReplaceGreaterValues([40, 60, 20, 0], 50));

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

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