This is my Javascript function:
function newgame()
{
var status = document.getElementById('status');
xTurn = true;
status.innerHTML = 'X\'s turn';
for(var x ==0; x < x++) {
for(var y ==0; y < y++) {
document.getElementById(x + '_' + y).value = ' ';
}
}
}
Error is identified at line for(var x ==0; x < x++) {
Please help me find what the error is.
This is the syntax of for loop
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
You can't use == here.You need to use = sign here. == compare the values and = is for assignment.Also your second condition is also missing in lop so It is a invalid loop statement.I think your desired loop could be like this
for(var x =0; x <(where you want to terminate) ;x++) {
for(var y =0; y < (where you want to terminate) ; y++) {
document.getElementById(x + '_' + y).value = ' ';
}
}
== is an equality check. You can't use it when you create a variable with var (and it looks like you are trying to assign 0 which would use =
You need also a second ; sign in the loop header. This is valid javascript syntax:
for(var x = x==0; x < x++;) {
for(var y = y==0; y < y++;) {
document.getElementById(x + '_' + y).value = ' ';
}
}
But it does only set x to 1 and not much more, because x < x++ is always false.
Related
This question already has answers here:
Concatenate string through for loop
(4 answers)
Closed 3 years ago.
My output is
1
1
2
1
2
3
…
The output I am looking for is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
var x,y;
for(x=1; x <= 5; x++){
for (y=1; y <= x; y++) {
console.log(y)
}
}
You could take a single loop with a part variable and one for the full string.
Then you need to add a space only if the string is not empty and add in each loop the new value and the actual part to the full string.
var i,
part = '',
full = '';
for (i = 1; i <= 5; i++) {
part += (part && ' ') + i;
full += (full && ' ') + part;
}
console.log(full);
Try with this code:
var x,y,z='';
for(x=1; x <= 5; x++){
for (y=1; y <= x; y++) {
z = z + y + ' ';
}
}
console.log(z);
Try the snippet below:
var str = ''
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= i; j++) {
str += `${j} `
}
}
console.log(str)
This should work for you:
var x, y, concatenatedString = '';
for(x = 1; x <= 5; x++) {
for (y=1; y <= x; y++) {
concatenatedString += `${y} `
}
}
console.log(concatenatedString)
You are console logging each time which puts it on a new line.
It's a better idea to store numbers in an array and then print out one by one.
var x, y, myArray[];
for (x = 1; x <= 5; x++) {
for (y = 1; y <= x; y++) {
myString += y.toString() + " ";
}
}
console.log(myString);
You could also place numbers in an array and output one by one.
The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');
I have a series of information that I am looking to cut down to size by looping the information. Here is the original code that is working:
$('#M1s1').css({'visibility': M1s1v});
$('#M1s2').css({'visibility': M1s2v});
$('#M1s3').css({'visibility': M1s3v});
$('#M1s4').css({'visibility': M1s4v});
$('#M1s5').css({'visibility': M1s5v});
$('#M1s6').css({'visibility': M1s6v});
$('#M1s7').css({'visibility': M1s7v});
$('#M2s1').css({'visibility': M2s1v});
$('#M2s2').css({'visibility': M2s2v});
$('#M2s3').css({'visibility': M2s3v});
$('#M2s4').css({'visibility': M2s4v});
$('#M2s5').css({'visibility': M2s5v});
$('#M2s6').css({'visibility': M2s6v});
$('#M2s7').css({'visibility': M2s7v});
$('#M3s1').css({'visibility': M3s1v});
$('#M3s2').css({'visibility': M3s2v});
$('#M3s3').css({'visibility': M3s3v});
$('#M3s4').css({'visibility': M3s4v});
$('#M3s5').css({'visibility': M3s5v});
$('#M3s6').css({'visibility': M3s6v});
$('#M3s7').css({'visibility': M3s7v});
$('#M4s1').css({'visibility': M4s1v});
$('#M4s2').css({'visibility': M4s2v});
$('#M4s3').css({'visibility': M4s3v});
$('#M4s4').css({'visibility': M4s4v});
$('#M4s5').css({'visibility': M4s5v});
$('#M4s6').css({'visibility': M4s6v});
$('#M4s7').css({'visibility': M4s7v});
$('#M5s1').css({'visibility': M5s1v});
$('#M5s2').css({'visibility': M5s2v});
$('#M5s3').css({'visibility': M5s3v});
$('#M5s4').css({'visibility': M5s4v});
$('#M5s5').css({'visibility': M5s5v});
$('#M5s6').css({'visibility': M5s6v});
$('#M5s7').css({'visibility': M5s7v});
And here is the for loops that I created to try and cut down the length of code and possibility of typing errors:
// set smc array(#M1s1, #M1s2, #M1s3, etc.)
var smc = [];
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
var smc[] = '#M' + m + 's' + s;
}
}
// set smcv array(#M1s1v, #M1s2v, #M1s3v, etc.)
var smcv = [];
for (mv = 1; mv < 6; mv++) {
for (sv = 1; sv < 8; sv++) {
var smcv[] = '#M' + mv + 's' + sv + 'v';
}
}
// loop to set visibility of small circles
for (i = 0; i < 35; i++) {
$(smc[i]).css({'visibility': smcv[i]});
}
I am really new to javascript loops and feel like I may be overlooking something basic or even a syntax error of some kind but can't put a finger on what the problem is. Any direction or assistance would be greatly appreciated!
UPDATE
Here is the final solution to my problem:
//set smc array(#M1s1, #M1s2, #M1s3, etc.)
var smc = [];
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
smc.push('#M' + m + 's' + s);
}
}
//set smcv array(#Ms1v, #M1s2v, #M1s3v, etc.)
var smcv = [];
for (mv = 1; mv < 6; mv++) {
for (sv = 1; sv < 8; sv++) {
smcv.push('M' + mv + 's' + sv + 'v');
}
}
//loop to set visibility of small circles
for (i = 0; i < 35; i++) {
$(smc[i]).css({'visibility': window[smcv[i]]});
}
You can't push value to array using var smc[] = 'something'.
Use smc.push( 'something' )
Lets say the M1s1v,M1s2v,.... values are coming from a json variable, something like this:
var x = {
M1s1v : "hidden",
M1s2v : "visibile",
...
}
then you can cut-short the code to something like this:
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
$('#M' + m + 's' + s).css({'visiblity':x['M'+m+'s'+s+'v']});
}
}
Hope it helps.
Say you have a two dimensional array, 5 x 7 for M and s holding something that will evaluate to true/false (boolean, 0, 1, empty string...).
var data = [][];
...
for (var M=0; M < data.length; M++) {
for (var s=0; s < data[M].length; M++) {
$('#M' + (M+1) + 's' + (s+1)).css({'visibility': data[M][s] ? 'visible' : 'hidden'});
}
}
You could "optimize" by using hard coded numbers instead of the lengths if you were centian of the dimensions.
Are there other ways to increment a for loop in Javascript besides i++ and ++i? For example, I want to increment by 3 instead of one.
for (var i = 0; i < myVar.length; i+3) {
//every three
}
Use the += assignment operator:
for (var i = 0; i < myVar.length; i += 3) {
Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.
For more information about each step of the for loop, check out the MDN article.
A for loop:
for(INIT; TEST; ADVANCE) {
BODY
}
Means the following:
INIT;
while (true) {
if (!TEST)
break;
BODY;
ADVANCE;
}
You can write almost any expression for INIT, TEST, ADVANCE, and BODY.
Do note that the ++ operators and variants are operators with side-effects (one should try to avoid them if you are not using them like i+=1 and the like):
++i means i+=1; return i
i++ means oldI=i; i+=1; return oldI
Example:
> i=0
> [i++, i, ++i, i, i--, i, --i, i]
[0, 1, 2, 2, 2, 1, 0, 0]
for (var i = 0; i < 10; i = i + 2) {
// code here
}
Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true or false.
When I use a for loop, I think of it as
for (var i = 0; i < 10; ++i) {
/* expression */
}
as being
var i = 0;
while( i < 10 ) {
/* expression */
++i;
}
for (var i = 0; i < myVar.length; i+=3) {
//every three
}
additional
Operator Example Same As
++ X ++ x = x + 1
-- X -- x = x - 1
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
You certainly can. Others have pointed out correctly that you need to do i += 3. You can't do what you have posted because all you are doing here is adding i + 3 but never assigning the result back to i. i++ is just a shorthand for i = i + 1, similarly i +=3 is a shorthand for i = i + 3.
For those who are looking to increment pair of numbers (like 1-2 to 3-4):
Solution one:
//initial values
var n_left = 1;
var n_right = 2;
for (i = 1; i <= 5; i++) {
console.log(n_left + "-" + n_right);
n_left =+ n_left+2;
n_right =+ n_right+2;
}
//result: 1-2 3-4 5-6 7-8 9-10
Solution two:
for (x = 0; x <= 9; x+=2) {
console.log((x+1) + "-" + (x+2));
}
//result: 1-2 3-4 5-6 7-8 9-10
The last part of the ternary operator allows you to specify the increment step size. For instance, i++ means increment by 1. i+=2 is same as i=i+2,... etc.
Example:
let val= [];
for (let i = 0; i < 9; i+=2) {
val = val + i+",";
}
console.log(val);
Expected results: "2,4,6,8"
'i' can be any floating point or whole number depending on the desired step size.
There is an operator just for this. For example, if I wanted to change a variable i by 3 then:
var someValue = 9;
var Increment = 3;
for(var i=0;i<someValue;i+=Increment){
//do whatever
}
to decrease, you use -=
var someValue = 3;
var Increment = 3;
for(var i=9;i>someValue;i+=Increment){
//do whatever
}
It's been a while since I wrote any Javascript. Is there a more elegant way to do this. Specifically want to get rid of the second loop:
<script>
var number = 0;
for (var i=1; i<11; i++) {
for (var x=1; x<11; x++) {
if (i==1) {
number = x;
} else {
number = Math.pow(i, x);
}
document.write(number + " ");
if (x == 10) {
document.write("<br>");
}
}
}
</script>
I would stick with 2 loops but i would change one if statement and move it after the 2nd loop and avoid document.write and insert it all at once to reduce the number of time you change the DOM
let result = ''
for (let i = 1; i < 11; i++) {
for (let x = 1; x < 11; x++)
result += (i==1 ? x : Math.pow(i, x)) + ' '
result += '<br>'
}
document.body.insertAdjacentHTML('beforeend', result)
Edit If you really don't want the 2nd loop:
let result = ''
// you must swap the condition to check for x instead of i
for (let i = 1, x = 1; x < 11; i++) {
result += (x==1 ? i : Math.pow(x, i)) + ' '
// and reset i and increase x yourself
if (i == 10) {
i = 0
x++
result += '<br>'
}
}
document.body.insertAdjacentHTML('beforeend', result)
Edit2 just for the fun: No for loops.
Just a recursive function :P
function build(i = 1, x = 1, res = '') {
res += (x == 1 ? i : Math.pow(x, i)) + ' '
i == 10 ? (x++, i=1, res += '<br>') : i++
return x == 11 ? res : build(i, x, res)
}
document.body.insertAdjacentHTML('beforeend', build())
In terms of 'elegancy', I'd go for for... in loops or map function. That doesn't solve your nested loop though.
On a side note, nested loops are not necessarily bad. If that's the correct way to implement the specific algorithm, then that's how it is.
Using Math.pow() is un-necessary overhead. Nested loops are not necessarily bad.
var number = 0;
for (var i=1; i<11; i++) {
document.write(i + " ");
number = i;
for (var x=2; x<11; x++) {
number = (i == 1) ? x : number * i;
document.write(number + " ");
}
document.write("<br>");
}
Another way of doing it with 1 loop only, tho not as clean:
var number = 0;
var x = 1;
var calc = 0;
var calcx = 1;
var increment = false;
for (var i=1; i<101; i++) {
increment = false;
calc = i % 10;
if(calc == 0){
calc = 10;
increment = true;
}
if (calcx==1) {
number = calc;
} else {
number = Math.pow(calcx, calc);
console.log(calcx+" "+calc);
}
document.write(number + " ");
if (i % 10 == 0) {
document.write("<br>");
}
if(increment){
calcx++;
}
}
Here's another way with only one loop:
[...Array(100)].map((_,i) => {
document.write(((i>9)?Math.pow(Math.floor((i+10)/10),(i%10)+1):i+1) + ' ' + ((i%10==9)?'<br>':''));
});