试着理解这个函数模式

trying to understand this function pattern

本文关键字:函数 模式      更新时间:2023-09-26

所以我试图写一个函数模式,创建以下模式最多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;
}
// 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');
}
http://jsfiddle.net/afmchdwp/

首先定义静态方法数组。Range,帮助我们在javascript中定义数字范围。

模式函数现在可以使用这个范围来创建您需要的数字。函数的第一行创建了一个范围从1..N(行起始号)。

第二行遍历该数组并转换每个值1..使用.join(),可以将每行的字符组合起来,也可以将每行本身组合起来。

更新2

这里是一个更新的小提琴没有逗号分隔的数字(使用闭包内的连接):http://jsfiddle.net/afmchdwp/1/