The array in JavaScript
Today more comprehensive learning to JS in the array, that is, arrays. Write a blog post to summarize the learning and use of some of the errors in the array and common APIs, to deepen the impression.
About the most comprehensive API for array here, MDN
Nanyi Ruan Teacher's array tutorial
Definition of array
Definition from MDN:
The array object of JavaScript is the global object used to construct the array, which is a higher-order object like a list
From the Nanyi teacher Tutorial definition:
An array is a set of values arranged in a sequential order. The position of each value is numbered (starting at 0), and the entire array is expressed in square brackets.
First, the array is the object , and secondly, he is arranged in order
- The difference between an array and an object
So what is the difference between an array and an object?
Let's take a look at this piece of code first:
We declare an array and an object separately, and we can see that arr === obj
the result is false
, and that their corresponding constructors are different.
The constructor of the array arr is an array, and obj corresponds to the constructor object, which is their most essential difference.
Therefore, we can also say that an array is an object that has a special prototype chain.
Declaration of Array
var arr = [1,2,3]arr //[1,2,3]
This allows us to create an array of length 3.
var arr = new Array(1,2,3)arr //[1,2,3]
It is important to note that when we use constructors to declare an array, it should be noted that different parameters cause inconsistent behavior.
var arr = new Array(3)arr //[empty × 3]var arr = new Array(3,3)arr //[3, 3]
Therefore, when we declare an array, it is not recommended to use constructors to generate new arrays, and it is better to use the array literals directly.
Pseudo-Array
If all the key names of an object are positive integers or 0, and have the length property, then the object is like an array, syntactically called an array-like object.
As mentioned in the previous article:
var arr = { ‘0‘:1, ‘2‘:2, ‘3‘:3}
How to tell if an array is a pseudo-array
- It's simple, the prototype of this array constructor is an array, and he is the real array; If the prototype of his constructor is object, he is a pseudo-array.
// 真数组arr.__proto__ === Array.prototype //true// 伪数组arr.__proto__ === Object.prototype //true
- Array.isarray ()
The Array.isarray method returns a Boolean value that indicates whether the parameter is an array. It can compensate for the insufficiency of the typeof operator.
var arr = [1, 2, 3];typeof arr // "object"Array.isArray(arr) // true
Array Common APIs
Nanyi Teacher's tutorial has a very detailed usage explanation, the whole copy no meaning, it is important to understand, if you do not remember to go directly to query on it.
- Push ()
- Pop ()
- Shift ()
- Unshift ()
- ForEach ()
- Sort ()
- Join ()
- Concat ()
- Map ()
- Filter ()
- Reduce
[JavaScript] The array in JavaScript