I'm try to copy the even numbers in an array and randomize the newly copied element inside the same for loop:
var arr=[0,1,2,3,4,5,6,7,8];
var arr2=[];
for(var i=0;i<arr.length;i++){
if(arr[i]%2==0){
arr2.splice(Math.random()*arr2.length,0,arr[i]);
}
}
document.write(arr2);
The concept is simple: insert the newly copied element at random position of the new array, but the serval output indicates it's not correct:
2,6,4,8,0
4,8,6,2,0
6,2,8,4,0
which always have 0 at the last. What's wrong with the code? Or is my concept wrong?