简体   繁体   中英

JavaScript equivalent to Ruby's .each

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?

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>`); }); 

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);
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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM