+ 5

Examples on how to use the forEach, reduce, map and filter methods in JavaScript

29th Nov 2018, 3:12 PM
David Danso
David Danso - avatar
5 Respuestas
+ 5
I can answer forEach for you! take a look at this code snip I have for a Discord bot I’m making: function multiplyCommand(arguments, recievedMessage){ if(arguments.length < 2){ recievedMessage.channel.send('I can\'t multiply that.') } let product = 1 arguments.forEach((value) => { product = product * parseFloat(value) }) recievedMessage.channel.send('The answer is ' + product.toString()) } The code is saying that for every value that is inputed, it will multiply it by the other values that are input. Simply put: forEach will execute any code inside the curly braces for every single thing in the parameters. Correct me if i’m wrong.
29th Nov 2018, 5:04 PM
Yosharu
Yosharu - avatar
+ 3
You can learn from Daniel's 10 Array method https://code.sololearn.com/WopAH9yrs62D/?ref=app His other tutorials: https://code.sololearn.com/WKFF4vOCr3mi/?ref=app
30th Nov 2018, 4:41 PM
Gordon
Gordon - avatar
+ 2
forEach is used to perform a function for each element in an array e.g Es6 : var fruits = ["apple", "banana"] ; fruits.forEach((fruit) =>{ console.log(`The fruit is ${fruit} `) ; } ) ; Or.. var fruits = ["apple", "banana"] ; fruits.forEach(function(fruit) { console.log("The fruit is " + fruit) ; } ) ; The forEach array method can e used in place of a for loop eg: Es6: var fruits = ["apple", "banana"] ; for(let fruit of fruits) { console.log(`The fruit is ${fruit} `) ; } , in the forEach, the parameter passed to your function is a variable that represents each element of your array, it can be named anything, it took me a while to understand too, but its nice to use, i also originally came here to search how to use the reduce array method, but ill just share what i know, andvin case u dont understand te es6 for...of loop, here's the equivalent : for(i = 0;i<fruits. length;i++) { console.log("The fruit is "+ fruits[i]) ; } Hope that helped
1st Aug 2020, 1:13 PM
Tekashi69{Oliseh}
Tekashi69{Oliseh} - avatar
30th Nov 2018, 4:43 PM
Calviղ
Calviղ - avatar