试着理解这个函数模式
trying to understand this function pattern
所以我试图写一个函数模式,创建以下模式最多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/
相关文章:
- Node.js使用Series函数(模式?)实现流控制时出现意外结果
- JavaScript 立即调用了函数模式差异
- Javascript立即调用了函数模式
- 如何在 Crockford 的新构造函数模式中共享“构造函数”功能
- 构造函数模式和原型模式之间的区别
- addEventListener用immediate函数模式调用函数两次
- 我想了解这个javascript函数模式
- 为什么实用模块&构造函数模式将其作为全局接受
- 带有私有变量的JavaScript构造函数模式
- JavaScript 构造函数模式
- 构造函数模式下的自执行函数
- 为什么我的JavaScript构造函数模式不能工作?
- 试着理解这个函数模式
- 基于一次性的自定义函数模式
- JS构造函数模式
- 简单构造函数模式
- jQuery事件触发器+构造函数模式
- return和new关键字构造函数模式的区别是什么?
- crockford的JavaScript构造函数模式真的应该更快吗?
- Javascript:混合构造函数模式和揭示模块模式