【问题标题】:A for loop with a logic or a syntax issue具有逻辑或语法问题的 for 循环
【发布时间】:2013-07-26 06:00:32
【问题描述】:

所以我试图将数组的长度作为字符串推送到另一个数组上。 我的逻辑是……对于 javascript

if    x = [1];
and   y = [1];

我想在 for 循环中将 x.length + 1 推送到 y 数组,这样它就变成了 1 12 123 第1234章

这就是我正在尝试的方式,但得到了阅读

function push() { [native code] } function push() { [native code] } function push() { [native code] } function push() { [native code] }

这是我的代码

for (i=0; i < 100; i++) {

        var x = [1];
        var y = [1];

            document.writeln(y.push.toString(x.length + 1));

    };

这是逻辑错误还是语法错误?

【问题讨论】:

  • 你希望y.push.toString 做什么?

标签: javascript for-loop syntax logic


【解决方案1】:

你正在写 y.push.toString

试试:

for (i=0; i < 100; i++) {
    var x = [1];
    var y = [1];
    y.push(x.length + 1)
    document.writeln(y);
};

但我认为你的意思是JSBIN Demo:

var y = [];    
for (i=0; i < 100; i++) {
    y.push(y.length + 1)
    document.writeln(y + '<br/>');
};

【讨论】:

  • 这很像我最终弄清楚的
【解决方案2】:

也许你正在尝试这样做

    var x = [1];
    var y = [1];
for (i=0; i < 100; i++) {
       document.writeln(y.push(x.length + 1));
};

var x = [1];
var y = [1];
for (i=0; i < 100; i++) {
        y.push(y.length + 1)
        document.writeln(y);
    }

var y = ""
for (i=1; i < 100; i++) {
        y += i
        document.writeln(y);
}

【讨论】:

  • 最后一个完美命中
  • 最后一个是我会怎么做的.. :)
【解决方案3】:

这当然是你想要的:

var y = [1];
for (i = 0; i < 10; i++) {
    var x = y[y.length-1].toString() + (y.length + 1);
    y.push(x);
} 
document.writeln(y.toString());

【讨论】:

  • 我喜欢它,这就是我想要做的。我也想出了另一种在每个数字之间加逗号的方法。请参阅下面的答案
  • 我认为你不能为此添加一个中断并将每个数字放在它自己的行上
【解决方案4】:

这是我得到它的方法

var y = [1];
    document.writeln(y + '<br>');
for (i=2; i < 101; i++) {
    y.push(i);
    document.writeln(y + '<br>' );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2020-12-01
    • 2014-08-15
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多