JavaScript相当于Ruby的.each

时间:2016-04-28 16:16:24

标签: javascript arrays 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是否具有与此类似的功能?

3 个答案:

答案 0 :(得分:2)

您正在寻找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>`);
});

答案 1 :(得分:1)

等效是

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

答案 2 :(得分: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);
});