The special features of arrays in JavaScript (1)

Arrays are the basic syntax of almost all programming languages. JavaScript lacks collection objects because of its grammatical features, and uses arrays relatively more.
Most people are already very familiar with the basic grammar knowledge of arrays. This article will not introduce its basic syntax and usage, but start with some special features of arrays in JavaScript, and through the introduction of these rare features, we will deepen our understanding of array knowledge.

basic introduction

First of all, as a start, we still need to briefly introduce arrays in JavaScript:

  • An ordered collection of data, the index value increases from 0
  • Has a length attribute
  • Array element values ​​can be of any type in JavaScript
  • It is dynamic and can add or subtract elements
  • Array elements can be looped, with a series of operable instance methods
  • Supports multidimensional arrays whose elements are arrays
  • Read elements 数组名[索引值]represented by

The above is the basic introduction to arrays, and most of them are familiar. Next, let’s take a look at some special features of arrays.

Array type and judgment

In JavaScript, there is no such data type as an array, so an array is essentially a special object whose type value will be returned object, as follows:

typeof [] // 'object'

Since the returned type is objectthe type, it is impossible typeofto judge whether a value or object is an array through the syntax, and other methods must be used to correctly judge the array object.

For detailed knowledge of typeof, see the blog post to understand the usage of typeof in js .

The method of judging as an array

There are many ways to judge whether an object is an array, but we generally use only two or three, and the most correct and effective ways are two.

correct way of judging

These two ways to correctly and effectively determine the array type are as follows:

  • Array.isArray()
    The syntax introduced by ES6 is specially used to judge whether the object type is an array. If it is, it returns true, otherwise it returns false. It is simple and easy to use.
  • Object.prototype.toString.call()
    is generally used in the JS grammar before ES6 to judge arrays in this way. Except for arrays, it can accurately judge almost all other JS data types.
Array.isArray([1, 2, 3]) // true
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call({
    
    }) // '[object Object]'

The above code is an example of these two effective methods, which can be accurately and effectively judged.
In the current front-end development, ES6 syntax is basically popular, and Array.isArray()it will be more convenient to use.

Introduced in other ways

In addition to the above two, there are several other judgment methods based on the prototype chain that can be used to judge arrays, but these methods are not accurate enough:

  • [] instanceof Array
    The instanceof operator is used here to indicate whether the given value is an instance of an array.
  • [].constructor === Array
    Whether the instance constructor for the given value is an array.
  • Array.prototype.isPrototypeOf ([])
    Whether there is an array on the prototype chain of the given value.
  • Object.getPrototypeOf([]) === Array.prototype
    Whether the prototype object of the given value is equal to the prototype object of the array.

These methods are similar in nature, but because the prototype chain can be modified, these methods are not recommended.
If you use instanceofthe judgment method:

[] instanceof Array // true
[] instanceof Object // true

In the above code, instanceofwhen the operator is used, an array instance belongs Arrayto and Objectare all established, because Object is on the prototype chain of Array.

Array index value and length

The array reads the element value through the subscript index value, and square brackets must be used, otherwise the element value cannot be read.

const arr = [1, 2, 3]
arr[1] // 2
arr.1 // Uncaught SyntaxError: Unexpected number

The above code, using arr.1the writing method, reports a syntax error, because it is illegal to use a single number as an identifier in JavaScript. For error types, see the Error object and custom error types in the blog post JavaScript .

As mentioned earlier, an array is a special object, and an object object can read elements through the key name, but the key name of the array can only be a number, so an error will be reported when reading it as an identifier. And if the object object uses a number as the key name, it cannot be read through the identifier:

const obj = {
    
     1: 'hello' }
obj.1 // Uncaught SyntaxError: Unexpected number

As shown in the above code, the object uses obj.1the way to read properties, but also reports the same error.

Index values ​​are strings

Arrays use square brackets to read element values, and Object objects can also read attribute values ​​through this method, so that even if the key name of the object is a number, it can be read normally:

const obj = {
    
     1: 'hello', key: 'world' }
obj[1] // 'hello'
obj['key'] // 'world'

In fact, the keys of the Object object in JavaScript are all string types, and the type of the array is object, so its index value (key name) can also use a string.

const arr = [1, 2, 3]
arr['1'] // 2
arr['2'] // 3

The above code, when using strings such as '1' and '2', can also correctly read the elements of the array.

But it should be noted that the index value of the array must be a value that can be automatically converted into a positive integer number. If it is other values, you need to pay attention.

Index values ​​are decimals, negative numbers

If the array uses decimals or negative numbers to read and write, what is the performance of the array? You can see the following code:

const arr = [1,2]
arr[-1] = 0
arr[2.0] = 5
arr[3.6] = 8
Array.isArray(arr) // true
arr // [1, 2, 5, -1: 0, 3.6: 8]
arr.length // 3
arr[-1] // 0
arr[3.6] // 0

The above code shows:

  • Using decimals 2.0can be automatically converted into positive integers, so it can be used as the third element of the array;
  • Using negative numbers -1and decimals that cannot be automatically converted to positive integers 3.6, both of these cases are used as the key-value pairs of the array and become the attributes of the array, but they are not included in the array elements, because the length attribute of the array is 3, which does not contain these two values.
  • Negative numbers -1and decimals 3.6are both used as strings. Similarly, they can also be used arr[true] = 50. The bool value here trueis also treated as the string 'true'.

Therefore, negative numbers or decimals cannot be used as index values ​​of arrays, but can be used as key-value pairs and read and written as attributes of arrays.

When the index value is other types such as string

If we use other types of values ​​such as strings and Boolean values ​​as subscript indexes for arrays, it will behave similarly to decimal negative numbers at this time.
That is, the array is used as an object, and these types of subscript indexes are all operated as attributes of the array object and can be read and written normally, but they are not elements of the array and are not counted in the length of the array.

const arr = [1]
arr['key'] = 0
arr['value'] = '是的'
arr.length // 1
arr // [1, key: 0, value: '是的']

The above code reflects the characteristics that the array belongs to the object type, and can add the properties of the key-value pair.

length property

length is the length attribute of the array, indicating the number of array elements, but please note that it is not read-only, but writable, that is, we can assign a value to the length attribute of the array:

[].length = 3
// 数组的长度被赋予为3

But there are a few points to note:

  • If the length value of the set array is less than the number of elements, the array will automatically delete all elements greater than the length value
  • If the length value of the set array is greater than the number of elements, the number of elements in the array will automatically increase to the length value, and the newly added elements are empty (return undefined)
  • If the length property of the array is set to 0, the entire array will be cleared and become an empty array
  • The length value of the array must be a positive integer (or a value that can be automatically converted to a positive integer), other values ​​are illegal, and an error will be reported when an illegal value is set.
    • Values ​​that can be automatically converted to positive integers include 2.0, '', true, false, '10'etc.
const arr = [1, 2]
arr.length = true
console.log(arr) // [1]

arr.length = -1 // VM307:1 Uncaught RangeError: Invalid array length

In the above code example,
the length value of the array is modified to be true, true can be converted to 1, the length of the array becomes 1, and one element is deleted;
when the array length is set to a negative number, an error is reported, invalid array length.

In addition, in addition to the above situations, one more thing we need to know is that the array has a maximum length.

the maximum length of the array

The maximum length that an array in JavaScript can assign is a 32-bit positive integer, that is, 2**32 - 1= 4294967295, calculated from 0, and the length minus 1.
When we set the length of the array to exceed the value of the maximum length, an error of invalid length will also be reported:

[].length = 4294967296 // Uncaught RangeError: Invalid array length

But if we use a number that exceeds the maximum length as a key to assign a value to the array, it can still be used, as shown in the following code:

const arr = []
arr[4294967296] = 1
arr // [4294967296: 1]

As mentioned earlier, this is because an array is essentially an object. When a number exceeding the maximum length range is used, the number will be used as the key name of an attribute of the array and can be automatically converted into a string. At this time, it is not an element of the array, nor is it counted in the length attribute of the array, just like the index value described above.

Guess you like

Origin blog.csdn.net/jimojianghu/article/details/128031232