Javascript 试图理解这个函数模式

Javascript 试图理解这个函数模式,javascript,Javascript,因此,我试图编写一个函数模式,它创建以下多达n行的模式。如果参数为0或负整数,则应返回“”即空字符串 123456 23456 3456 456 56 6 我试图理解这个问题的解决方案如下: function pattern(n){ var output=""; for(i=1;i<n+1;i++){ for(j=i;j<n+1;j++){ //what is the purpose of this j loop? output

因此,我试图编写一个函数模式,它创建以下多达n行的模式。如果参数为0或负整数,则应返回“”即空字符串

123456
23456
3456
456
56
6
我试图理解这个问题的解决方案如下:

function pattern(n){  
 var output="";   
   for(i=1;i<n+1;i++){ 
     for(j=i;j<n+1;j++){    //what is the purpose of this j loop? 
       output += j;   
     }
     if(i!=n) output +="\n";   //I know \n can jump to next line,  but what does this if statement mean?  why I!=n? 
   }
 return output;
}
函数模式(n){
var输出=”;
对于(i=1;i

首先,我们定义静态方法Array.range,它帮助我们在javascript中定义数字范围

pattern函数现在可以使用此范围创建所需的数字。 函数的第一行创建一个范围,范围为1..n(行的起始编号)

第二行遍历此数组,并将每个值1..n转换为从linenumber到n的范围。使用.join(),可以组合每行的字符,也可以组合行本身

更新2


这里是一个没有逗号分隔的数字的更新fiddle(在闭包中使用join):

j循环控制当前行号的起始位置。i循环控制行数。final if语句表示不在最后一行上添加换行符。
// function definition
function pattern(n){  
 // declare a variable to collect the lines
 var output="";
   // there are n lines
   for(i=1;i<n+1;i++){ 
     // each line starts with the linenumber and ends with n
     // so take a loop from i to n
     for(j=i;j<n+1;j++){
       // collect the numbers of each line as a string in the declared variable 
       output += j;   
     }
     // if i!=n means: not the last line
     if(i!=n) output +="\n";
   }
 // return the result of this function
 return output;
}
Array.range = function(start, end) {
    return Array.apply(null, Array(end+1)).map(function (_, i) {return i;}).slice(start);
}

function pattern(n){
    var startValues = Array.range(1,n);
    return startValues.map(function(i) { return Array.range(i,n); }).join('\n');
}