Does JavaScript have an equivalent to Ruby's .each method?
For example Ruby:
arr = %w(1 2 3 4 5 6 7 8 9 10)
arr.each do |multi|
sum = multi * 2
puts "The sum of #{multi} ^ 2 = #{sum}"
end
#<=The sum of 1 ^ 2 = 11
The sum of 2 ^ 2 = 22
The sum of 3 ^ 2 = 33
The sum of 4 ^ 2 = 44
The sum of 5 ^ 2 = 55
The sum of 6 ^ 2 = 66
The sum of 7 ^ 2 = 77
The sum of 8 ^ 2 = 88
The sum of 9 ^ 2 = 99
The sum of 10 ^ 2 = 1010
Does JavaScript have an equivalent to something like this?
Heretic Monkey
12.2k7 gold badges63 silver badges133 bronze badges
asked Apr 28, 2016 at 16:16
13aal
1,6941 gold badge22 silver badges48 bronze badges
3 Answers 3
You are looking for Array.prototype.forEach function
var arr = ['1', '2', '3', '4', '5'];
arr.forEach(multi => {
var sum = multi.repeat(2);
console.log(`The sum of ${multi} ^ 2 = ${sum}`);
});
Working example:
var arr = ['1', '2', '3', '4', '5'];
arr.forEach(multi => {
var sum = multi.repeat(2);
document.write(`The sum of ${multi} ^ 2 = ${sum}</br>`);
});
answered Apr 28, 2016 at 16:28
isvforall
8,9166 gold badges39 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
An equivalent is
myArray.forEach(callback);
where callback is your callback function. In this case, the function that is going to be executed for each element.
Note that callback can be passed in to ways:
First:
myArray.forEach(function(element, index, array){
//Operations
console.log(element)
});
Second:
function myCallback(element, index, array){
//Operations
console.log(element)
}
myArray.forEach(myCallback);
answered Apr 28, 2016 at 16:29
Iván Rodríguez Torres
4,4593 gold badges33 silver badges49 bronze badges
Comments
var arr=[1, 2, 3, 4, 5,6, 7, 8, 9, 10];
arr.forEach(function(element,index){
var sum = element.toString() + element.toString();
console.log("The sum of "+ element+"^ 2 = "+sum);
});
answered Apr 28, 2016 at 16:31
Sergio Fandino
4453 silver badges7 bronze badges
Comments
lang-js
foreach? Is it the same as using theforloop?forEachon the internet? You are expected to do a minimum of research before asking questions on SO. See How to Ask.javascript equivelent to Rubys.eachbefore asking, but thanks.