I want to exchange the first value for the last, the second with the last but one and so on.
Like this:
Array = [0,1,2,3,4,5,6]
Array[0] –> Array[7] –> Array = [6,1,2,3,4,5,0]
I try to make this, but it didn’t work, it only makes the array blank:
var vetor = [],temp=0,b=vetor.length-1;
for (var i = 0;i<20;i++) {
vetor[i] = Number(prompt("Digite um nĂºmero: " + i));
temp = vetor[i];
vetor[i] = vetor[b];
b--;
console.log(vetor[b]);
}
alert(vetor);
2
Answers
The function works by creating a temp var to store the first element of the array – array[0]. Then it assigns the value of the last element to the first element and assigns the value of the temporary variable to the last element.
Reference:
length
I just created a function with paramateres(array and an iteration). For example if you want to change second and sixth element you must change iteration as 1.
Example:
Array is [0, 1, 2, 3, 4, 5, 6]
changeArray(array, 0) will change 0 index and 6 index element.
Array is [6, 1, 2, 3, 4, 5, 0]
changeArray(array, 1) will change 1 index and 5 index element so it will be like [6, 5, 2, 3, 4, 1, 0]
I added a constraint because you can not divide forever. I calculated how many iteration will be changed. If user adds any iteration which one is invalid then it will return the array itself.