I have this:
ooooo
ooooo
ooooo
ooooo
ooooo
Put o
on everything except the middle so it turns into this:
ooooo
o o
o o
o o
ooooo
Is there anyway I can do that in Javascript? My code currently is: HTML:
<input type = 'text' id = 'box' placeholder = 'Enter n' onkeyup = 'bigbox();'/>
<br><br>
<div id="output"></div>
Script:
function bigbox() {
number = document.getElementById('box').value;
display = document.getElementById("output");
for(let j = 0; j<number; j++) {
for(let i = 0; i<number; i++)
text += "o";
text += "<br>";
}
display.innerHTML = text;
You could add if one of the indices is zero or plus one equal to the wanted site of the square, then take a border character or space.
Basically this line
text += i === 0 || i + 1 === size || j === 0 || j + 1 === size ? "o": " ";
contains three parts:
An addition assignment +=
, which takes an expression and adds it to the left hand side variable.
text += someExpression
A conditional (ternary) operator ?:
which takes an expression and checks if this is truthy (like any number except zero or NaN
, any non empty string, an object or array, true
) or falsy (like zero/NaN
, ''
, null
, undefined
, false
).
If truthy, it take the value after the ?
and if falsy the value after :
.
It is a kind of short form of an if
statement with getting an expression.
expression ? alternative1 : alternative2 // code
truthy -> alternative1 // result
falsy -> alternative2
A condition part. The conditions are a connected with logical OR ||
, this returns the first truthy value, or the last falsy one.
condition1 || condition2 || condition3 || ...
The conditions check the indices and if zero or the greatest valid value, then you hit a border, otherwise you are inside of the square.
function bigbox(size) {
var display = document.getElementById("output"),
text = "";
size = +size;
for (let j = 0; j < size; j++) {
for (let i = 0; i < size; i++) {
text += i === 0 || i + 1 === size || j === 0 || j + 1 === size ? "o": " ";
}
text += "<br>";
}
display.innerHTML = text;
}
<input type="text" id="box" onchange="bigbox(this.value)">
<pre id="output"></pre>