【发布时间】:2015-09-02 23:50:01
【问题描述】:
我的输出需要是:
01 02 03 04 05 06 07 08
09 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
我有点缺乏练习,开始时遇到了困难。到目前为止,我将引导您完成我的思考过程,但如果您能推动我朝着正确的方向前进,那就太棒了!
首先,我想我需要建立cell-object模型,像这样;
var mod = {val: 0, first: 0, second: 0};
第二,我需要创建一个包含 32 个这些对象的数组。
var arr = [];
var i = 1;
function createArray(){
while (i < 33) {
if (i<10){
mod = {
val: i,
first: 0,
second: i
}
} else {
mod = {
val: i,
first: i.toString().split('').reverse().pop(),
second: i.toString().split('').pop()
}
arr.push(mod);
}
i++;
}
};
createArray();
var result = '';
arr.forEach(function(space){
space = space.first.toString() + space.second.toString();
if(result.length < 24){
result += space + ' ';
} else {
console.log(result);
result = '';
}
});
对我来说,这产生了一个奇怪的结果:
01 02 03 04 05 06 07 08
10 11 12 13 14 15 16 17
19 20 21 22 23 24 25 26
这里发生了什么?它跳过了09 和18,但为什么呢?我只是看不到它。
编辑
正如 @zerkms 指出的那样,我在输入 SO 时出现了错误。 i++ 应该在 while 循环内;否则会产生无限循环。
【问题讨论】:
-
你粘贴的代码有无限循环。
-
当行达到 24 的长度时 - 你会丢失一个值,因为你没有将它保存在任何地方。
-
代码在我运行时没有无限循环,所以让我仔细检查一下
-
@zerkms,不...只是不。
-
嗯,它确实有
while (i < 33) {并没有改变i在它的身体。
标签: javascript node.js algorithm console.log