javascript - 返回一个字符串而不是循环打印语句

标签 javascript

我是 Javascript 新手,我很好奇如何在字符串中存储值然后返回它。在下面的示例中,选择了 2 个数字,例如 2 和 8,程序应返回 2x1 =2、2x2=4,..... 一直到 2x8 =16。显然,这可以通过像我一样不断循环打印语句来完成,但是我如何能够将所有值存储在字符串中,然后返回字符串。

function showMultiples (num, numMultiples)
{
for (i = 1; i < numMultiples; i++)
  {
    var result = num*i;
    console.log(num + " x " + i + " = " + result+ "\n"); 
  }
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2,8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3,2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5,4));

最佳答案

function showMultiples(num, numMultiples) {
  // the accumulator (should be initialized to empty string)
  var str = "";
  for (i = 1; i < numMultiples; i++) {
    var result = num * i;
    // use += to append to str instead of overriding it
    str += num + " x " + i + " = " + result + "\n";
  }
  // return the result str
  return str;
}

var mulOf5 = showMultiples(5, 10);

console.log("multiples of 5 are:\n" + mulOf5);

运算符+=将a值(右操作数)与左操作数的前一个值相加,并将结果存储在后面。所以这两行是相同的:

str = str + someValue;
str += someValue;

关于javascript - 返回一个字符串而不是循环打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916608/

相关文章:

php - javascript 如果负面条件不起作用

javascript - 解析 JSON 字符串时仅获取特定键并忽略其他键(无框架库)

javascript - JS - 专注于 b 标签

javascript - 与 document.domain 和 CORS 相关的这种不一致行为的解释是什么?

javascript - 如何检测图像是否可见?

javascript - 使用 applyBindingsToNode 从元素绑定(bind)调用 viewmodel 函数失败

如果在离线时加载/刷新页面,JavaScript 后台同步将停止工作

javascript - 我如何在React中选择导入/导出

javascript - 当我给他们 ID 时 SQL 没有更新

javascript - 在 d3 map 投影周围创建一个弯曲的边界