简体   繁体   中英

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?!

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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