For the cycle against foreach

I am still new to programming and it is hard for me to find different options for / foreach. A more technical exclamation for each cycle counts how many times this is needed - unlike the code below.

Say I was a sample for loop as follows:

var i = result = 0; for (var i = 2; i < process.argv.length; i++) { result = result + Number(process.argv[i]); } console.log(result); 

How would this code change if it were a foreach statement? Is this explanation correct? Or is there more?

Thank you at Advance.

+7
foreach for-loop
source share
3 answers

The foreach loop goes through all the elements in the array and gives them to you one by one, without having to iterate over the iteration variable using "i". For example, you can do this:

 var result = 0; process.argv.forEach(function(element){ result = result + element; }); 

There is a difference between your code and this code: your code skipped the first two elements because "i" started with 2. This is harder to do in the foreach loop, and if you need to, you must stick to the loop.

The foreach loop sets counters for you. Comfortable but less flexible. It always starts with the first element and ends with the last. One great thing to notice is that we also don’t need to do anything like β€œ[i]”. The array element is pulled and passed to our function.

In conclusion, the foreach loop is simply simplified for the loop for cases where you need to look at each element of the array.

I personally find that the foreach loop in node.js is ugly, as it is not an operator, but just a function related to arrays. I prefer how they look like php, where they are part of the language:

 $result = 0; foreach ($process as $element) { $result = $result + $element; } 

But this is just a personal taste.

+2
source share

for and forEach are not your options. You can also use reduce

 var result = process.argv.slice(2).reduce(function(sum, n) { return sum + parseInt(n, 10); }, 0); console.log(result); 

Try and see

 $ node reduce.js 1 2 3 6 
+3
source share

I'm not sure about this, but maybe this is how you declare "i" twice (one in the first line and then again in the for loop).

So it just works with a simple loop:

 var result = 0; for (var i = 2; i < process.argv.length; i++) { result += Number(process.argv[i]); } console.log(result); 

If you want to use forEach:

 var result = 0; process.argv.slice(2).forEach(function(element) { result += Number(element); }); console.log(result); 

A trick is a slice function that returns a new array without the first two elements.

0
source share

All Articles