How to concatonate string in iteration loop [duplicate] - javascript

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.

Related

How to write a number pattern generator program in JavaScript?

I have to make a pattern like this:
=========1=========
=======22122=======
====33322122333====
4444333221223334444
I have not found the logic yet. I tried to code it, but the output is different.
Here is the output of my working code snippet:
----1-----
---123----
--12345---
-1234567--
123456789-
function nomor3(input){
let temp = '';
for (let x = 1; x <= input; x++){
for (let y = input ; y > x; y--){
temp += "-";
}
for (let z = 1; z <= (x * 2) - 1; z++){
temp += z;
}
for (let k = input; k >= x; k--){
temp += "-";
}
temp += '\n';
}
return temp
}
console.log(nomor3(5));
The logic for each level - say 4th level - it begins with the digit of the level to the count of the digit, then one less and so on. So line 4 looks like 4444-333-22-1 and backwards (dashes added for demonstration).
So here we build each line like that, starting from the biggest so we know its length so we can center other lines with dashes. We use arrays here and reversing them because it's easier than strings. But lastly we join so we have a string.
function pyramide(level) {
var len = null;
var result = [];
while (level > 0) {
var arr = [];
for (var i = level; i > 1; i--) {
for (var repeat = 0; repeat < i; repeat++) {
arr.push(i)
}
}
var str_level = arr.join("") + "1" + arr.reverse().join("");
if (len === null) {
len = str_level.length;
}
while (str_level.length < len) {
str_level = "-" + str_level + "-";
}
result.push(str_level);
level--;
}
return result.reverse().join("\n");
}
console.log(pyramide(5))

Js Multi-dimensional Array setting value oddly

I've made a multidimensional array with Array constructor and Array.fill method.
I cannot figure out where the problem is, but this code doesn't work as I want.
function loadChunk(){
for(var x = 0; x< 3; x++){
for(var y= 0; y < 3; y++){
console.log(x+","+y);
console.log((world[x][y]).loaded);
if(!(world[x][y]).loaded){
world[x][y].loaded=true;
}
}
}
}
function createWorld(w, d){
var worldz = new Array(d * 2 + 1);
var world = new Array(w * 2 + 1);
world.fill(worldz);
for(var x = 0; x< w * 2+ 1; x++){
for(var z = 0; z < d * 2 + 1; z++){
world[x][z]= { loaded: false };
}
}
return world;
}
var world = createWorld(1, 1);
Start();
function Start(){
loadChunk();
}
You can see what is happening with console.
With my view, no true should be written on console.
The problem is, if I edit world[0][n],then world[1 or more][n] changes too.
Replace your createWorld function with this:
function createWorld(w, d){
var world = new Array(w * 2 + 1);
for(var x = 0; x< w * 2+ 1; x++){
// each item of the array requires a new instance
// you should not use fill method in this situation
world[x]=new Array(d * 2 + 1);
for(var z = 0; z < d * 2 + 1; z++){
world[x][z]= { loaded: false };
}
}
return world;
}
function loadChunk() {
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 3; y++) {
console.log(x + "," + y, (world[x][y]).loaded);
if (!(world[x][y]).loaded) {
world[x][y].loaded = true;
}
}
}
}
function createWorld(w, d) {
var world = [];
for (var x = 0; x < w * 2 + 1; x++) {
world[x] = [];
for (var z = 0; z < d * 2 + 1; z++) {
world[x][z] = {loaded: false};
}
}
return world;
}
var world = createWorld(1, 1);
Start();
function Start() {
loadChunk();
}
The problem that you expirience is that you fill "rows" of world with the same array, so world[0] === world[1] && world[1] === world[2] because array variable worldz is holding a reference
The best way to learn your problem is doing next thing:
function createWorld(w, d){
var worldz = new Array(d * 2 + 1);
var world = new Array(w * 2 + 1);
world.fill(worldz);
for(var x = 0; x< w * 2+ 1; x++){
for(var z = 0; z < d * 2 + 1; z++){
world[x][z]= { loaded: false };
debugger;
}
}
return world;
}
And inspecting in chrome debugger what happens with world variable on a first step
The reason why a change of world[0][0] also changes world[1][0] and world[2][0] (same for other indecees of worldz) is that world.fill(worldz) makes all elements of world the same identical object (Array) worldz.
To avoid this every element of world should be a new Array like eg:
for(n=0,max=world.length;n<max;n++) {world[n] = new Array(d * 2 + 1);}

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.

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
}

Javascript: getting rid of nested loop

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>':''));
});

Categories

Resources