Which function would you use - Javascript - javascript

I'm new to javascript and I have the following code:
<p id="demo"></p>
<script>
var text = "";
var x = 1;
var y = 1;
while(x < 9) {
text += "<br>" + x +"," + y;
x++;
}
document.getElementById("demo").innerHTML = text;
</script>
It prints out a list of coordinates:
1,1
2,1
3,1
4,1
5,1
6,1
7,1
8,1
The question is once it gets to 8,1 What would you use to get it to continue to:
1,2
2,2
3,2
4,2
5,2
6,2
7,2
8,2
then
1,3
and so on until it reaches 3,4 (this could be variable) then it stops.
In an ideal world I would be able to get it to go up to a maximum of 8,12.

You could use another while structure for the seconde value.
var text = "",
x,
y = 1;
while (y <= 12) {
x = 1;
while (x <= 8) {
text += "<br>" + x + "," + y;
x++;
}
y++;
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>
Or you could use a for statement
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
var text = "",
x,
y;
for (y = 1; y <= 12; y++) {
for (x = 1; x <= 8; x++) {
text += "<br>" + x + "," + y;
}
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

Write it like this:
var text = "", x,y;
for (y=1; y<= 12; y++) {
for (x=1; x<= 8; x++) {
text += "<br>" + x + "," + y;
}
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

You can nest loops. The best solution here is to use two nested for loops:
let text = '';
for (let y = 1; y <= 12; ++y) {
for (let x = 1; x <= 8; ++x) {
text += "<br>" + x + "," + y;
}
}
document.getElementById("demo").innerHTML = text;
<output id="demo"></output>
As you can see, it stops at 8,12, exactly like you wanted :)
You can find more about different types of loops and iteration on MDN.

Here is a fun solution. It is not what I would do but for educational purposes, so take it for what it is.
It uses Array.prototype.reduce on inner and outer arrays. The accumulated result of the inner array on each iteration gets added to the accumulator of the outer array. The inner reduce is where all the actual data is added. The outer reduce just accumulates the inner results.
It uses some ECMAScript 2015 features also like the spread syntax and arrow functions.
str = [...Array(12)].reduce((s, _, i) =>
s + [...Array(8)].reduce((ss, _, j) =>
ss + (j + 1) + ',' + (i + 1) + "\n", ""),
"");
console.log(str);
I used "\n" instead of "<br>" so that it shows up in console.
Don't actually use this. Its just to show different way. I would use a nested loop in practice.
Have fun!

Related

Trigonometric Interpolation returns NaN

I'm a musician, who's new to programming. I use JavaScript inside Max Msp (hence the bang() and post() functions) to create a trigonometric interpolation, interpolating between given equidistant points (for testing, only values of sine from [0, 2π) and returning values from the same points). When I run the code, it returns NaN, except for x = 0, as my tau() function returns only 1 in this special case. Could it be, that it has something to do with summing Math.sin results?
var f = new Array(9);
var TWO_PI = 2*Math.PI;
bang();
function bang() {
for(var i = 0; i < f.length; i++) {
f[i] = Math.sin(i/f.length*TWO_PI);
//post("f[" + i + "]: " + Math.round(f[i]*1000)/1000 + "\n");
}
var points = new Array(f.length);
for(var i = 0; i < points.length; i++) {
var idx = i/points.length*TWO_PI;
points[i] = [i, p(idx)];
//post("p[" + points[i][0] + "]: " + Math.round(points[i][1]*1000)/1000 + "\n");
}
console.log("p(2): " + p(2/points.length*TWO_PI) + "\n");
}
function p(x) {
var result = 0;
for(var k = 0; k < f.length; k++) {
result += f[k]*tau(k, x);
}
return result;
}
function tau(k, x) {
var dividend = sinc(1/2*f.length*(x-k/f.length*TWO_PI));
var divisor = sinc(1/2*(x-k/f.length*TWO_PI));
var result = dividend/divisor;
if(f.length%2 == 0) result *= Math.cos(1/2*(x-k/f.length*TWO_PI));
if(x == 0) return 1;
return result;
}
function sinc(x) {
return Math.sin(x)/x;
}
In your tau function, if x equals k / f.length * TWO_PI (which it will since x is multiples of 1 / points.length * TWO_PI) your sinc function divides by 0, making divisor equal to NaN, which then propagates.
You have to be a bit careful in implementing sinc to avoid dividing by 0. One way is to say that if x is small enough we can replace sin(x) by the first few terms of its taylor series, and all the terms are divisible by x.
I don't know javascript but here is the function in C in case it is of use
#define SINC_EPS (1e-6)
// for small x,
// missing sinc terms start with pow(x,4)/120, and value close to 1
// so the error too small to be seen in a double
double sinc( double x)
{ if ( fabs(x) < SINC_EPS)
{ return 1.0 - x*x/6.0;
}
else
{ return sin(x)/x;
}
}

How to concatonate string in iteration loop [duplicate]

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.

Javascript syntax error identified 'for' keyword

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.

Javascript only goes through the first iteration of a for statement

I've been trying to figure out why this 'for' only loops once. Having spent about 6 hours re-writing conditions, I was wondering if you could give me a hand with spotting the problem.
Thanks in advance for any piece of advise and your time !
var k;
var i = 1;
function stergeLinie(k) {
var tabel = document.getElementById('produse');
var rowCount = tabel.rows.length;
var row = document.getElementById("tr" + k);
row.parentNode.removeChild(row);
var t = rowCount;
for (y = k; y < t; y++) {
document.getElementById("nrcrtid" + (y + 1)).value = y;
document.getElementById("nrcrtid" + (y + 1)).name = "nr_crt" + y;
document.getElementById("nrcrtid" + (y + 1)).id = "nrcrtid" + y;
document.getElementById("prodid" + (y + 1)).name = "prod" + y;
document.getElementById("prodid" + (y + 1)).id = "prodid" + y;
document.getElementById("umid" + (y + 1)).name = "um" + y;
document.getElementById("umid" + (y + 1)).id = "umid" + y;
document.getElementById("cantitateid" + (y + 1)).name = "cantitate" + y;
document.getElementById("cantitateid" + (y + 1)).id = "cantitateid" + y;
document.getElementById("pretid" + (y + 1)).name = "pret" + y;
document.getElementById("pretid" + (y + 1)).id = "pretid" + y;
document.getElementById("pretfaraTVAid" + (y + 1)).name = "pretfaraTVA" + y;
document.getElementById("pretfaraTVAid" + (y + 1)).id = "pretfaraTVAid" + y;
document.getElementById("tvaid" + (y + 1)).name = "tva" + y;
document.getElementById("tvaid" + (y + 1)).id = "tvaid" + y;
document.getElementById("tr" + (y + 1)).id = "tr" + y;
document.getElementById("buton" + (y + 1)).id = "buton" + y;
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
stergeLinie(y);
}
document.getElementById("butons" + y).id = "butons" + (y);
}
alert(y);
document.getElementById("tr" + i).style.height = "100%";
i--;
}
The main problem is this line:
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
stergeLinie(y);
}
y is getting incremented each time the loop runs (y++), so when the button is actually clicked, y has the value it had on the final iteration - which is just enough to get the loop to run once.
Another issue you're having is this line:
var rowCount = tabel.rows.length;
Where your ids are 1-based, that is the lowest number is 1, whereas the length property is 0 based. If there are 4 rows, rowCount will be 3, meaning that your loop will never reach 4 because the condition is y < rowCount.
Here's a cut down version of your script: http://jsfiddle.net/trolleymusic/XTzjb/ -- I also had to run the function once at the beginning to bind the click in the way that you're doing it.
Here's an updated version that loops correctly: http://jsfiddle.net/trolleymusic/Z8UYp/
var k;
var i = 1;
function stergeLinie(k) {
console.log("k: " + k);
var tabel = document.getElementById('produse');
// Add 1 to the rowCount because the elements have been assigned
// ids starting with 1, and length is 0-based
var rowCount = tabel.rows.length + 1;
var row = document.getElementById("tr" + k);
row.parentNode.removeChild(row);
var t = rowCount;
console.log(t, k);
for (var y = k; y < t; y++) {
console.log("Loop: " + y);
// If the elements don't exist anymore because they were removed
// skip the loop
if (!document.getElementById("butons" + (y + 1))) {
continue;
}
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
// Get the number out of the
// id of the element that was clicked
var x = parseInt(this.id.replace("butons",""));
console.log("x: " + x);
stergeLinie(x);
}
}
}
metadings helpfully added below that you could use a closure for y (http://jsfiddle.net/trolleymusic/dxy6N/)
for (var y = k; y < t; y++) {
(function (y) {
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
console.log(y);
stergeLinie(y);
}
}(y));
}
It looks much more complicated, but it's not really. You're putting all of the actions into another function, and passing the value of y to that function as an argument - that means that y is not the same variable as the y that you're incrementing in the loop, it belongs to the function inside the loop. This is closure. The accepted answer to this question: How do JavaScript closures work? gives an excellent explanation of closure.

Can a for loop increment/decrement by more than one?

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
}

Categories

Resources