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.