• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript How to alternate values from two variables?

simong1993

Active Coder
Staff Team
Guardian
Java im not much help with but here is the general logic in Python and 99% of the time its quite simple to transfer to Java :D
Python:
var1,var2 = [],[]
var1 = list(str(12345))
var2 = list(str(67890))
while_len = len(var1)
i = 0

while i < while_len:
    print(var1[i])
    print(var2[i])
    i+=1
 

Ghost

Active Coder
The answer above me uses Python, not JS. They posted the wrong type of code, but as they said - their answer is very similar to what we can do in JS.

Here's a working example:
Code:
var a = 1234;
var b = 5678;
a = a.toString();
b = b.toString();
var newstr = '';
for(var x = 0; x < a.length; x++){
    newstr += a[x];
    newstr += b[x];
}
console.log(newstr);

If you want to use the similar style to str() (from Python) instead of .toString() then you can use the JS built in String():
Code:
var a = 1234;

var b = 5678;

a = String(a);

b = String(b);

var newstr = '';

for(var x = 0; x < a.length; x++){

    newstr += a[x];

    newstr += b[x];

}

console.log(newstr);
 
Last edited:

Top