开发者

Javascript combine arrays or strings

开发者 https://www.devze.com 2023-01-22 04:58 出处:网络
I have the following dynamically generated strings: var stringA = [\"a1\", \"a2\", \"a3\" ... \'a400\' ... \'a600\']; // length 600

I have the following dynamically generated strings:

var stringA = ["a1", "a2", "a3" ... 'a400' ... 'a600']; // length 600
var stringB = ["b1", "b2", "b3" ... 'b400']; // length 400

How can I get an Array or string of both combined like this:

var myString = ["a1b1", "a2b2", "a3b3" ... "a400b400", "a401" ... "a600开发者_运维技巧"]


You can do something like this:

var result = [], len = Math.max(stringA.length, stringB.length);
for(var i=0; i < len; i++) {
    result.push((stringA[i] || "") + (stringB[i] || ""));
}

You can test it out here, the || "" is to prevent getting undefined as a string on the for the array that's shorter. The Math.max() call is to allow either A or B to be longer, it'll iterate to the end of either, just as A is longer in the question.


I don't think there's anything built into the Array object that will do it for you, you'll have to do the loop. The loop is trivial, though:

var index, length;
var result = [];
// assertion: arrayA.length === arrayB.length
result.length = arrayA.length; // Helps performance in some implemenations, harmless in others
for (index = 0, length = arrayA.length; index < length; ++index) {
     result[index] = arrayA[index] + arrayB[index];
}

(I've renamed stringA -> arrayA and stringB -> arrayB to avoid confusion.)

If the arrays are different lengths or some of the entries in the arrays are undefined (which is totally possible, JavaScript arrays are sparse), you'll want to handle that in the loop, e.g.:

var index, length, Apresent, Bpresent;
var result = [];
result.length = Math.max(arrayA.length, arrayB.length); // Helps performance in some implementations, harmless in others
for (index = 0, length = result.length; index < length; ++index) {
     Apresent = arrayA.hasOwnProperty(index);
     Bpresent = arrayB.hasOwnProperty(index);
     if (Apresent && Bpresent) {
         result[index] = arrayA[index] + arrayB[index];
     }
     else if (Apresent) {
         result[index] = arrayA[index];
     }
     else if (Bpresent) {
         result[index] = arrayB[index];
     }
}

If the arrays are sparse and they both happen to be sparse at the same index, the resulting array will also be sparse.


If you do not need to retain the the items in the original 2 arrays then the code below works really well. It does not have a predetermined limit to the number of iterations in the for loop which means that the stringA and StringB array could continue to grow in size while this code is running.

var myString = [];
for(var answer; answer = (stringA.shift() || "") + (stringB.shift() || "");) {
    myString.push(answer);
}


var myString = [];

for (var i=0;i<stringA.length;i++){
     myString[i] = stringA[i] + stringB[i];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消