JavaScript 相当于 Ruby 的 .each

JavaScript equivalent to Ruby's .each

JavaScript 是否有等同于 Ruby 的 .each 方法?

例如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

JavaScript 有类似这样的东西吗?

您正在寻找 Array.prototype.forEach 函数

var arr = ['1', '2', '3', '4', '5'];
arr.forEach(multi => {
    var sum = multi.repeat(2);
    console.log(`The sum of ${multi} ^ 2 = ${sum}`);
});

工作示例:

var arr = ['1', '2', '3', '4', '5'];
arr.forEach(multi => {
    var sum = multi.repeat(2);
    document.write(`The sum of ${multi} ^ 2 = ${sum}</br>`);
});

等价于

myArray.forEach(callback);

其中 callback 是您的回调函数。在这种情况下,将为每个元素执行的函数。

注意回调可以通过以下方式传递:

第一个:

myArray.forEach(function(element, index, array){
    //Operations
    console.log(element)
});

第二个:

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