Array of JavaScript study notes (1)

Array Basics

An overview of the array

1. Array syntax

An array is an ordered set of values. The position of each value is numbered (starting at 0).
var arr=[1,2,3] //arr[0]=1
Any type of data can be put into an array.

 var arr=[
            1,
            'a',
            undefined,
            null,
            true,
            {'name': 'jack','age': 18},
            function(){console.log(fn)}
        ]
arr[5]//对象:{name: "jack", age: 18}
arr[6]//函数:ƒ (){console.log(fn)}

Multidimensional Arrays

var a = [[1, 2], [3, 4]];
        console.log(a[0][0])//1
        console.log(a[1][1])//4

2. Characteristics of arrays

The array is an object, and typeofthe operator returns the type of the object
array. The speciality of the array is that its key name is a set of integers (0, 1, 2...) arranged in order.

var arr = ['a','b','c'];
        console.log(typeof(arr))//object
         console.log(Object.keys(arr))// ["0", "1", "2"]

In the above code, you can see that the key names of array members are fixed (the default is always 0, 1, 2...)
The JavaScript language stipulates that the key names of objects are always strings, so the key names of arrays are actually strings. The reason why it can be read numerically is because non-string key names will be converted to strings.


3. length property

The length property of an array returns the number of members of the array.

JavaScript uses a 32-bit integer to hold the number of elements in an array. This means that there are at most 4294967295 array members (2^32 - 1), which means that the maximum value of the length property is 4294967295.

As long as it is an array, it must have a length property. This property is a dynamic value equal to the largest integer in the integer key name plus 1.

Change the length of the array by setting the value of length
. Set the length property to 0 to clear the array.
If the length is set to be greater than the current number of elements in the array, the length of the array will increase to this value, the newly added positions are empty, and the newly added positions will return undefined.

The value of length can only be a positive integer, other values ​​will report an error

It is worth noting that since an array is essentially an object, you can add properties and property values ​​to the array, but this does not affect the value of the length property.


4. in operator

The operator in that checks for the existence of a key name works for objects as well as for arrays.

var arr=['a','b','c']
        console.log(1 in arr)//true 
        console.log(3 in arr)//false

The in operator returns false if a position in the array is empty.

var arr=['a','b','c']
        console.log(1 in arr)//true 
        console.log(3 in arr)//false
        arr[100]=2
        console.log(100 in arr)//true
        console.log(99 in arr)//false
        console.log(101 in arr)//false

5. for...in loop and array traversal The
for...in loop can not only traverse objects, but also arrays, because arrays are also objects.

var arr=['a','b','c']
        arr.dd='d'
        for(let i in arr){
            console.log(i)//0,1,2,dd
            console.log(arr[i])//a,b,c,d
        }

It is common to use a for loop to iterate through an array


6. Array-like

If all keys of an object are positive integers or zero, and have a length property, then the object behaves much like an array, and is syntactically called an "array-like object".
"Array-like objects" are not arrays because they don't have array-specific methods.

The fundamental characteristic of "array-like objects" is that they have a length property. This length property is not a dynamic value and will not change as the member changes.

Method to convert array-like to array

  • var arr = Array.prototype.slice.call(arrayLike);
 var obj={
           0: "a",
           1: "b",
           2: "c",
           3: "d",
           "length": 4
       }
       console.log(obj instanceof Array)//false
       var arr=Array.prototype.slice.call(obj)
       console.log(arr instanceof Array)//true

Array-like methods can also be invoked through the call() method.

var obj={
           0: "a",
           1: "b",
           2: "c",
           3: "d",
           "length": 4
       }
      Array.prototype.forEach.call(obj,(value,key)=>console.log(key+':'+value))
//       0:a
//       1:b
//       2:c
//       3:d

Strings are also array-like objects, so they can also be iterated over with Array.prototype.forEach.call.

 Array.prototype.forEach.call('string', (str,key)=>console.log(key+':'+str))
        // 0:s
        // 1:t
        // 2:r
        // 3:i
        // 4:n
        // 5:g

The call() method is slower than using the array's native forEach directly, so it's better to convert the array-like array to a real array first, and then call the array's forEach method.


2. Array object

1. How to declare an array

Array is JavaScript's native object, and it is also a constructor that can be used to generate new arrays.

var arr =new Array(3);//length:3Equivalent to var arr=Array(3);
using the above method to generate a new array is not recommended

It is recommended to use this method to generate arraysvar arr = [1, 2];


2. Array methods

2.1 Array.isArray()
The Array.isArray method returns a boolean value indicating whether the parameter is an array.


2.2 valueOf(), toString()
The valueOf method is a method owned by all objects, which means evaluating the object. The valueOf method of different objects is not consistent, and the valueOf method of an array returns the array itself.

The toString method is also a general method for objects, and the toString method of an array returns the string form of the array.


2.3 push(), pop()
The push method is used to add one or more elements at the end of the array and returns the length of the array after adding new elements.
The pop method is used to remove the last element of the array and return that element. Using the pop method on an empty array will not report an error, but return undefined.


2.4 shift(), unshift()
The shift method is used to delete the first element of the array and return the element.
The unshift method is used to add an element at the first position of the array and returns the length of the array after adding the new element.


2.5 join()
The join method uses the specified parameter as the delimiter, and returns all the array members as a string.
This method can also be used for strings or array-like objects via the call method.


2.6 concat()
The concat method is used to combine multiple arrays. It adds the members of the new array to the back of the original array members, and returns a new array with the original array unchanged.
In addition to arrays as parameters, concat also accepts other types of values ​​as parameters, which are added to the end of the target array.


2.7 reverse()
The reverse method is used to reverse the array elements and return the changed array.


2.8 slice()
The slice method is used to extract a part of the target array and return a new array, the original array remains unchanged.
arr.slice(start, end);
slice has no parameters and returns a copy of the original array.


2.9 splice()
The splice method is used to delete a part of the original array members, and can add new array members at the deleted position, and the return value is the deleted element.

arr.splice(start, count, addElement1, addElement2, ...);

The first parameter of splice is the starting position of the deletion (starting from 0), and the second parameter is the number of elements to be deleted. If there are more arguments, it means that these are the new elements to be inserted into the array.


2.10 sort()
sort method sorts array members

 var arr = [1,7,3,5,9,6];
        arr.sort(function(a,b){
            return a-b
        })
        console.log(arr)// [1, 3, 5, 6, 7, 9]
var arr = [
            {name:"张三",age:18},
            {name:"王五",age:3},
            {name:"李四",age:9}
        ];
        arr.sort(function(a,b){
            return a.age-b.age
        })
        console.log(arr)
       // [{name:"王五",age:3},{name:"李四",age:9},{name:"张三",age:18}]

2.11 map()
The map method passes all the members of the array into the parameter function in turn, and then returns the result of each execution as a new array.

var arr=[1,2,3,4]
    var arr1=arr.map(function(n){
        return n+1
    })
    console.log(arr1)//[2, 3, 4, 5]
    console.log(arr)//[1, 2, 3, 4]

The map method accepts a function as a parameter. When the function is called, the map method passes it three parameters: the current member, the current position, and the array itself.


2.12 forEach()
The forEach method is very similar to the map method, and also executes the parameter function on all the members of the array in turn. However, the forEach method does not return a value, it is only used to manipulate data. That is to say, if the purpose of traversing the array is to get the return value, then use the map method, otherwise use the forEach method.

The usage of forEach is the same as the map method. The parameter is a function, which also accepts three parameters: the current value, the current position, and the entire array.

var arr=[1,2,3,4]
    arr.forEach(function(value,key){
        console.log(key+':'+value)
    })

2.13 filter()
The filter method is used to filter the members of the array, and the members that satisfy the conditions form a new array and return.
Its parameter is a function, all array members execute the function in turn, and the members whose return result is true form a new array to return. This method does not change the original array.


2.14 some(), every()
These two methods return a boolean value, which means to judge whether the members of the array meet a certain condition.

They accept a function as an argument, and all array members execute that function in turn. The function accepts three parameters: the current member, the current position, and the entire array, and returns a boolean value.

The some method is that as long as the return value of a member is true, the return value of the entire some method is true, otherwise it returns false.
The every method is that the return value of all members is true, and the entire every method returns true, otherwise it returns false.


2.15 reduce(), reduceRight() The
reduce method and reduceRight method process each member of the array in turn, and eventually accumulate to a value. The difference is that reduce is processed from left to right (from the first member to the last member), reduceRight is processed from right to left (from the last member to the first member), the others are exactly the same.

var arr=[1,2,3,4]
    arr.reduce(function(a,b){
        console.log(a+b)//3,6
        return a+b//15
    })
//15

2.16 indexOf(), lastIndexOf()
The indexOf method returns the position of the first occurrence of the given element in the array, or -1 if it does not appear.
The indexOf method can also accept a second parameter, which represents the starting position of the search.

The lastIndexOf method returns the position of the last occurrence of the given element in the array, or -1 if it does not appear.
These two methods cannot be used to search for the position of NaN, i.e. they cannot determine whether an array member contains a NaN.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325126382&siteId=291194637