JavaScript 相当于 Ruby 的 .each

标签 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 有类似的东西吗?

最佳答案

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

关于JavaScript 相当于 Ruby 的 .each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920199/

相关文章:

javascript - Javascript 中的视差问题

Javascript navigator.mediaDevices.getUserMedia 将源移动到前面

javascript - 如何在 javascript/jquery 中创建多维数组?

grails - 通过迭代使每个标记

jquery - 显示与父级相同类的图像,与列表项的 ID 相同

javascript - 使用正则表达式的 jQuery 验证插件自定义方法

javascript - Aurelia 验证器不更新 UI

c++ - 如何初始化二维字符数组

javascript - jQuery 切片负索引不起作用

javascript - Lodash 从另一个对象追加对象而不进行替换