I have two arrays : A E B
A = [1,2,3...]
B = [7,5,1...]
When I do this subtraction it has the correct subtraction return:
console.log(A[0] - B[0]);
But when I play in the loop it does not work:
while (i = 0) {
A[i] - B[i]
}
I have two arrays : A E B
A = [1,2,3...]
B = [7,5,1...]
When I do this subtraction it has the correct subtraction return:
console.log(A[0] - B[0]);
But when I play in the loop it does not work:
while (i = 0) {
A[i] - B[i]
}
Let's write this code in a more organized, modern and avoid problems? And then we'll fix the two major mistakes in it. Always use var
to declare variables (or let
).
You are assigning within the condition, you can not (in general) do the assignment before entering the loop, and even create complicators to get into the loop. It is not incrementing i
, so it would not come out of the same element, and entering the loop would never go out. Not to mention that just subtracting is doing nothing useful, or you save in a variable, or you have to print to have some use.
var a = [1, 2, 3];
var b = [7, 5, 1];
var i = 0;
while (i < 3) console.log(a[i] - b[i++]);
This code works, it is correct, but it is not robust, it is not generic, solves only this case. I did this not to create confusion with new concepts or to present another way to solve the problem. I used only i++
there to make the increment. Usually when you have this need you use for
instead of while
.
An addendum for beginner. The other answer shows quite curious and even interesting things to use in some scenarios, but it is not necessary (nor did I see if it is right), it is inefficient and complicates the solution for anyone who even masters basic syntax and algorithm control. >
There are two viable options, the first one, which I think is better and cleaner with the map () function:
var resultado = A.map(function(element, index) {
return element - B[index];
});
The map () function traverses each its array and returns a value after processing whatever is inside the callback function. The 'element' parameter refers to the value it is currently accessing and the 'index' to the position.
If you have not yet learned or are not accustomed to using the functions map (), filter () and reduce () , you can also do this:
A.forEach(function(element, index, array) {
array[index] = element - B[index];
})
The forEach function also runs through the entire array A , it would be like a For, except in that you define how many iterations you want them to be made, forEach always traverses the total number of Array positions (unless you manipulate this).