This is the fourth day of my participation in the August Text Challenge.More challenges in August


preface

In the next article, we will look at the contents of THE JS array in detail. This section covers “splitting and concatenating arrays”, the previous portal


Subset splicing and splitting


concat()

Concatenate two or more arrays and return a new array. It doesn’t change the original array. The concat() method is used to merge arrays.

Syntax: New array = array 1.concat(array 2, array 3…) ;

const arr1 = [1, 2, 3]; const arr2 = ['a', 'b', 'c']; Const arr3 = [' PJ', 'PJ']; const result1 = arr1.concat(arr2); const result2 = arr2.concat(arr1, arr3); console.log('arr1 =' + JSON.stringify(arr1)); console.log('arr2 =' + JSON.stringify(arr2)); console.log('arr3 =' + JSON.stringify(arr3)); console.log('result1 =' + JSON.stringify(result1)); console.log('result2 =' + JSON.stringify(result2)); // As you can see from the printed result, the original array has not been modified. arr1 = [1, 2, 3]; arr2 = ['a', 'b', 'c']; Arr3 = [' PJ', 'PJ']; result1 = [1, 2, 3, 'a', 'b', 'c']; Result2 = [' a ', 'b', 'c', 1, 2, 3, 'small only front-end siege lion', 'Di'].Copy the code

Rest(…)

ES6 gives me a much easier way to use… This expansion syntax merges two arrays. As follows:

const arr1 = [1, 2, 3]; const result = ['a', 'b', 'c', ...arr1]; console.log(JSON.stringify(result)); // print result: ["a","b","c",1,2,3]Copy the code

To learn more about Rest usage, see this article. πŸ”₯Rest parameters and extension operators


join()

Function: Converts an array to a string, returning the converted string (without changing the original array).

Extension: The join() method can specify a concatenation, implemented as an argument. A concatenate is a string. If no concatenate is specified, it is used by default as a concatenate, which has the same effect as toString().

Syntax: new string = original array. Join (parameter); // Optional

var arr = ['a', 'b', 'c']; var result1 = arr.join(); Var result2 = arr.join('-'); var result2 = arr.join('-'); // Use the specified string as the concatenation console.log(typeof arr); // Prints the result: object console.log(typeof result1); // Prints the result: string console.log('arr =' + json.stringify (arr)); console.log('result1 =' + JSON.stringify(result1)); console.log('result2 =' + JSON.stringify(result2)); / / print the arr = [" a ", "b", "c"] result1 = a, b, c result2 = a - b - cCopy the code

split()

Splits a string into an array of characters using the specified delimiter. It doesn’t change the original string.

Note that split() is a string method, not an array method.

Syntax: New array = str.split(separator);Copy the code

Note: The split() method is used a lot in real development scenarios and is used a lot. Be careful to distinguish between slice and splice. You can’t be stupid and not know

\