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/