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?
nickf
548k199 gold badges660 silver badges727 bronze badges
asked Jun 8, 2012 at 7:49
man_or_astroman
6581 gold badge17 silver badges39 bronze badges
-
Do you have myarray[0] and my2ndarray[0]? E.g. Are there duplicate keys?Scott Stevens– Scott Stevens2012年06月08日 07:51:05 +00:00Commented Jun 8, 2012 at 7:51
-
Yes, it's possible, what have you tried?gdoron– gdoron2012年06月08日 07:51:34 +00:00Commented Jun 8, 2012 at 7:51
-
1yes it is, you just did :) why cant you just loop those arrays?meo– meo2012年06月08日 07:51:51 +00:00Commented Jun 8, 2012 at 7:51
3 Answers 3
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('&');
answered Jun 8, 2012 at 7:54
nickf
548k199 gold badges660 silver badges727 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Jun 8, 2012 at 7:55
Steve
3,0907 gold badges41 silver badges63 bronze badges
Comments
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.
answered Jun 8, 2012 at 7:54
jbrtrnd
3,8435 gold badges27 silver badges41 bronze badges
1 Comment
Scott
In this example, the variable 'sep' will be leaked to the global scope. Unless that's your intention, the two variables 'stringArray' and 'sep' should be defined individually. Also, nickf's answer will be more performant, array operations are generally faster than string concatenation.
lang-js