Javascript concatenates arrays or strings

I have the following dynamically generated lines:

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 as concatenated like this:

var myString = ["a1b1", "a2b2", "a3b3" ... "a400b400", "a401" ... "a600"]
+3
source share
4 answers

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

Here you can test it , || ""is to prevent getting undefinedas a string for an array that is shorter, the call Math.max()should allow either A, or Bbe longer, it will iterate to the end, just like Amore in the question.

+3
source

, - Array, , . :

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

( stringAarrayA stringBarrayB).

, undefined ( , JavaScript ), , :

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

, , .

0

2 , . for, , stringA StringB , .

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

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

Source: https://habr.com/ru/post/1771464/


All Articles