简体   繁体   中英

A for loop with a logic or a syntax issue

So I'm trying to push the length of an array as a string onto another array. My logic is this... for javascript

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

and I want to push x.length + 1 to the y array in a for loop so it becomes 1 12 123 1234

this is how I'm trying to do it but getting a read out of

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

here is my code

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

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

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

    };

is this a logic error or a syntax error?

you are writing y.push.toString

Try:

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

But I think what you meant was JSBIN Demo :

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

maybe you are trying to do this

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

or

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

or

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

Surely this is what you want:

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());

Here's how I got it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM