我的脚本可以打印三角形数字的模式(例如1,3,6,10,...),但我想将公式存储(n * (n + 1)) / 2在一个被调用的变量中,formula而不是在if-else语句中多次写入.
/* Current script */
var pat = document.getElementById("pattern");
var nMax = 10; // max number of intervals
for (var n = 1; n <= nMax; ++n) {
if (n != nMax)
// insert comma and space after each interval
pat.innerHTML += (n * (n + 1)) / 2 + ", ";
else
// append ellipsis after last interval
pat.innerHTML += (n * (n + 1)) / 2 + ",…"; …Run Code Online (Sandbox Code Playgroud)javascript ×1