function resolve(array) { for(var i = 0; i < array.length; i++){ if(array[i]%2 === 0){ var tempEl = array[i+1]; array[i+1] = array[i]; array[i] = tempEl; } } return array; } resolve([2,3,4,5,57,8,7]);
- general step-by-step debugging here would help - Grundy
- Add a description of what this code should do - Grundy
- probably an array of even numbers to output or odd - stackanon
- @stackanon, some exchange is not there if the number is even, it looks like some sorting, but which is not clear :) - Grundy
- @Grundy - group odd and even numbers? - Igor
|
2 answers
The problem with this code is that by finding one even number, it will move endlessly to the end of the array.
Why infinite?
Because when an even number is the last element in the array, executing the code
var tempEl = array[i+1]; array[i+1] = array[i]; array[i] = tempEl;
another i+1
element with the value undefined is added to the array, and an even number changes places with it and again ends at the end and at the next iteration everything repeats.
|
Apparently the problem is in this manual.
for(var i = 0; i < array.length; i++)
Do so
for(var i = 0; i < array.length-1; i++)
|