Home > Web Front-end > JS Tutorial > body text

How to connect js arrays

醉折花枝作酒筹
Release: 2021-08-11 10:23:53
Original
6073 people have browsed it

In the previous article, we learned about the method of converting elements in the array into strings. Please see "How to use the tostring method to convert js arrays into strings". This time we will learn about the method of connecting arrays. You can refer to it if necessary.

We have talked about many methods of array objects in js before, but we have never said how to connect arrays. Today we will talk about it.

First let’s look at a little chestnut.

<script>
var arr = new Array(3); 
arr[0] = "one";
arr[1] = "two";
arr[2] = "three";
console.log(arr);
var nums = new Array(3);
nums[0] = "one";
nums[1] = "two";
nums[2] = "three";
console.log(nums);
var perpos=arr.concat(nums);
console.log(perpos);
console.log(arr);
console.log(nums);
</script>
Copy after login

The result of this little chestnut is

How to connect js arrays

Take a good look at this example, the result is "Array(3)"-"Array( 3)"-"Array(6)"-"Array(3)"-"Array(3)", as you can see. We first output each array, then output the connected array, and then output each array separately. Observe, is there anything strange or other about this result?

We found that this method only connects two arrays. The two arrays have not changed, but only created an array with a new length and new content.

After understanding this method, let’s take a closer look at this method.

The concat method creates a new array consisting of elements in the called object. The order of each argument is either the argument's elements (if the argument is an array) or the argument itself (if the argument is not an array). It does not recurse into nested array parameters. The concat method does not alter this array or any array provided as an argument, but instead returns a shallow copy containing a copy of the same elements combined with the original array.

Let’s take a look at the grammatical structure of this method.

var 新数组名称=第一个数组名称.concat(需要合并的数组)
Copy after login

If the parameter is omitted, concat will return a shallow copy of the existing array calling this method.

That’s all. If you need it, you can read: javascript advanced tutorial

The above is the detailed content of How to connect js arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template