简体   繁体   中英

How can I add strings to array in javascript

I wanna create an array in javascript which looks like this:

[0,0,0,0,0,1,1,0,0,1,1,1,1,0,0],[0,0,0,0,1,1,1,1,0,1,0,1,1,1,0],[0,0,0,0,1,1,1,1,0,1,0,0,1,1,0],[0,0,0,0,0,1,1,0,1,0,1,0,1,0,0]

My problem is that I don't know how to add the opening and closing square brackets to the start and the end of the output string.

here's my code:

game = new Array();
for(row=0;row<matrix.length;++row){ 
        game[row]=matrix[row].join(','); 
    }
    document.getElementById('jsvalue').value=game.join('],[');
    document.getElementById('name2').value = name;

I tried a few things, but they didn't seem to work and all I got were errors or this output:

0,0,0,0,0,1,1,0,0,1,1,1,1,0,0],[0,0,0,0,1,1,1,1,0,1,0,1,1,1,0],[0,0,0,0,1,1,1,1,0,1,0,0,1,1,0],[0,0,0,0,0,1,1,0,1,0,1,0,1,0,0

How could I add them? Is there a simple array method that I missed and would solve my problem?

Thanks in advance!

It looks like you are trying to set the value of an HTML element to the format you described in your question. However, you are not setting the value of that HTML element to an Array - you are setting it to a string. the .join function outputs a string. If indeed you want the value to be set to a string formatted in the way you described, then you could take advantage of .join, but have to do a little bit in addition to what you are doing:

    game = new Array();
    for(row=0;row<matrix.length;++row){ 
        game[row]= "[" + matrix[row].join(',') + "]";
    }
    document.getElementById('jsvalue').value=game.join(',');
    document.getElementById('name2').value = name;

If you are using join to create the string, then why not just manually add the brackets? For example: document.getElementById('jsvalue').value= '[' + game.join('],[') + ']';

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