Thursday, June 2, 2022

Js - A snippet of code explained

        for(let product of products){
            const subArray = product.split(':');
            const name = subArray[0];
            const price = Number(subArray[1]);
            total += price;

And what means that snippet, for beginning I thought that are create an matrix but not, what happens is that, the for will make all the product inside the array products, be stayed in the program and so the array have 5 products that in the for is used an variable that I declare right in the parentehses of the 'for', so I made product that you see I have to declare let, will be every element of the products, why? Because this is the for...of, here I have a very simple structure that will run all the elements of the array without I need say the size of the array, making very simple if you already understand what is an for....of, or would be that way for (let i=0; I<=products.length; i++) {products [I];} this way I have an structure that run all the array by each element of the array.

First let me say that product is an local variable, that will just run inside the for, out of the for isn't product is products[0], products[1] ...., so the product is an invention that runs the machine for me for a structure very simple. 

And what happens inside the for I declare ->cons subArray = product.split(':') -> You might think that I create an matrix with subArray[0][0] and so on, but not here I create an array every element with only 2 elements, so I create 5 times one array named subArray with only two elements, one the name and other the price, so just bellow still inside the for I declare const for name and const for price, so I five times create an subArray and extract the 1st element for the name and the second element for the price and this will be store all the time, the next isn't erasing the previous but being replacing in the next li until the end.

If was a matrix the pants will be the product[0][0], but the socks would be the[1][0] they combine in the last index but not in the 1st so doesn't work unless, unless you create an more hard to do structure of for that after you create the matrix make another for that runs all the matrix but catch the index by the second index is like products[i][n] so I run one and run all that have inside the first index to catch an specific second index, much harder of do.

Rute Bezerra de Menezes Gondim





No comments:

Post a Comment