javascript将数组转换为字符串

时间:2012-06-08 07:49:30

标签: javascript arrays

你好,我有2个数组,我想把它们放在一个字符串中。我的数组可以取值从0到maxNum-1。所以我要说myArray1 [i]和myArray2 [i] 我想制作一个这样的字符串:

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]);

有可能吗?

3 个答案:

答案 0 :(得分:3)

使用循环的力量。

var output = [];

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

答案 1 :(得分:1)

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);

这假设两个数组的长度相等

答案 2 :(得分:0)

使用循环:

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

var stringArray应包含您的数组值。