0

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!

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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('],[') + ']';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.