2

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
3
  • @isvforall Can you give me an example of using foreach? Is it the same as using the for loop? Commented Apr 28, 2016 at 16:22
  • Can you look up forEach on the internet? You are expected to do a minimum of research before asking questions on SO. See How to Ask. Commented Apr 28, 2016 at 16:24
  • @MikeMcCaughan I actually looked up javascript equivelent to Rubys.each before asking, but thanks. Commented Apr 28, 2016 at 16:34

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1
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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.