
上QQ阅读APP看书,第一时间看更新
Joining multiple arrays
Consider a scenario where you have different arrays and you need to join all of them into a single array. We could iterate each array and add each element to the final array. Fortunately, JavaScript already has a method that can do this for us, named the concat method, which looks as follows:
const zero = 0; const positiveNumbers = [1, 2, 3]; const negativeNumbers = [-3, -2, -1]; let numbers = negativeNumbers.concat(zero, positiveNumbers);
We can pass as many arrays and objects/elements to this array as we desire. The arrays will be concatenated to the specified array in the order that the arguments are passed to the method. In this example, zero will be concatenated to negativeNumbers, and then positiveNumbers will be concatenated to the resulting array. The output of the numbers array will be the values -3, -2, -1, 0, 1, 2, and 3.