man_or_astroman
man_or_astroman

Reputation: 648

javascript convert array to string

Hello i have 2 arrays and and i want to put them in a single string. My arrays can take values from 0 to a maxNum-1. So lets say i have myArray1[i] and myArray2[i] I want to make a string like this:

string = "myArray1ID" + 1 + "=" + (myArray1[1])
    + "&" +"myArray2ID" + 1 + "=" + (myArray2[1])
    + "&" + "myArray1ID" + 2 + "=" + (myArray1[2])
    + "&" + "myArray2ID" + 2 + "=" + (myArray2[2])
    + ......
    + "myArray1ID" + (maxNum - 1) + "=" + (myArray[maxNum-1])
    + "&" "myArray2ID" + (maxNum - 1) + "=" + (myArray2[maxNum-1]);

Is it possible?

Upvotes: 0

Views: 2338

Answers (3)

Steve
Steve

Reputation: 3080

var myString = '';

for(var i; i < myArray1.length; i++){
  myString += "myArray1ID" + i + "=" + (myArray1[i]) + "&";
  myString += "myArray2ID" + i + "=" + (myArray2[i]) + "&";
}

//remove trialing "&"
var myString = myString.substring(0, myString.length-1);

This assumes that both arrays are of equal length

Upvotes: 1

jbrtrnd
jbrtrnd

Reputation: 3833

Use a loop :

var stringArray = sep = ""; 
for(var i = 1; i < maxNum; i++) {
    stringArray += sep + "myArray1ID" + i + "=" + myArray1[i];
    stringArray += "&myArray2ID" + i + "=" + myArray2[i];
    sep = "&";
}

The var stringArray should contains your array values.

Upvotes: 0

nickf
nickf

Reputation: 546045

Use the power of loops.

var output = [];

for (var i = 1; i < maxNum; ++i) {
    output.push(
        'myArray1ID' + i + '=' + myArray1[i],
        'myArray2ID' + i + '=' + myArray2[i]
    );
}
return output.join('&');

Upvotes: 3

Related Questions