Chapter 3 special object array in JS

Posted by Markto on Wed, 22 Dec 2021 11:21:20 +0100

Chapter 3 special object array in JS

For the previously learned data type, only one value can be stored (for example: Number/String). We want to store multiple values in a variable. How should we store them?

The so-called array is to arrange multiple elements (usually of the same type) in a set in a certain order. Then this set is called array.

1.1 creation of array

// Create an array literal
var arr1 = []; //Empty array
// Create an array of 3 values with multiple array items separated by commas
var arr2 = [1, 3, 4]; 
// Create an array of 2 strings
var arr3 = ['a', 'c']; 
console.log(arr1);
console.log(arr2);
console.log(arr3);

// You can get the length of the array through the length property of the array
console.log(arr3.length);
// You can set the length attribute to change the number of elements in the array
arr3.length = 0;

console.log(arr3[0]);//undefined

The elements of an array can be any type of data. Therefore, sometimes the value of an element in the array is an array, and such an array is called a multi-dimensional array. If there are only other types of data in the array without other array values, such an array is called a one-dimensional array;

Generally, arrays are nested N layers, which are called N-dimensional arrays. The most common are two-dimensional arrays, three-dimensional arrays and four-dimensional arrays. Arrays exceeding one dimension are generally called multi-dimensional arrays;

The larger the dimension value of the array, the higher the complexity. Try to avoid arrays with high dimension values in development;

var arr1 = [a,b,c]; // One dimensional array
var arr2 = [a,b,c,[d,e]]; // Two dimensional array
var arr3 = [a,b,c,[d,e,[f,g]]]; // 3D array
var arr4 = [a,b,c,[d,e,[f,g,[h,t,y]]]]; // Four dimensional array

1.2 get array elements

// Format: array name [subscript] 	 Subscript is also called index
// Subscript starts at 0
// Function: get the value of the subscript corresponding to the array. If the subscript does not exist, return undefined.
var arr = ['red',, 'green'];
arr[0];	// red
arr[1];	// undefined subscript position has no data
arr[2]; // green
arr[5]; // The maximum subscript of this array is 2, so undefined is returned
// Get data of multidimensional array
var arr = ['Monkey D Luffy','Nami',['Bucky','female emperor',['Sasuke','Joba']]];
console.log(arr[2][2][0]); //Sasuke

1.3 traversal array

Traversal: throughout all, each element of the array is accessed once, which is called traversal.

Basic syntax for circular array traversal:

for(var i = 0; i < arr.length; i++) {
	// Fixed structure of array traversal
}

for loop example:

var arr1 = [1, 3, 4]; 

for(var i = 0;i<arr1.length;i++){
    console.log(arr1[i]);
}

While loop example:

var arr1 = [1, 3, 4]; 

var i = 0;
while(i<arr1.length){
    console.log(arr1[i]);
    i++;
}

1.4 adding elements for array modification

// Format: array name [subscript / index] = value;
// If the subscript has a corresponding value, the original value will be overwritten. If the subscript does not exist, an element will be added to the array.
var arr = ["red", "green", "blue"];
// Replace red with yellow
arr[0] = "yellow";
// Added a new value of pink to the array
arr[3] = "pink";

1.5 array operation cases

Case 1: sum all numbers in the array

//Sum
var arr = [10, 20, 30, 40, 50];
//Define variable storage and
var sum = 0;
for (var i = 0; i < arr.length; i++) {
    sum += arr[i];
}
console.log("Hewei:" + sum);

Case 2: get the maximum value in the array

//Maximum
var arr = [10, 20, 30, 40, 50, 60];
//Suppose the value in this variable is the largest
var maxNum = arr[0];
//Traversal array
for (var i = 0; i < arr.length; i++) {
    //judge
    if (maxNum < arr[i]) {
        maxNum = arr[i];
    }
}
console.log("The maximum is:" + maxNum);

Case 3: traverse all even numbers in the array

// Traverse all even numbers in the array
var arr = [1,2,3,4,5,6,7];
for(var i=0;i<arr.length;i++){
    //judge
    if(arr[i]%2==0){
        console.log(arr[i]);
    }
}

Case 4: convert an array into a string and split it with |

//Splice a | after each name in the array, and then output it as a string
var names = ["Kakashi", "Sasuke", "Miss Luo Yu feng", "Naruto", "Heizaki Ichigo"];
var str = "";//An empty string used to store the result of the last splice
//Keep traversing the data of the array and splicing strings
for (var i = 0; i < names.length - 1; i++) {
    str += names[i] + "|";//How to splice strings
}
str += names[names.length - 1];
console.log(str);

Summary:

Array is a collection of multiple data, including one-dimensional array and multi-dimensional array. You can use literal method to create an array, use subscript to obtain array element data, and use for or while loop to traverse array elements;

2.1 Array object

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

2.1. 1 common attributes and methods

length property: returns the number of members of the array.

var arr = ['a', 'b'];
console.log(arr.length) // 2

common method

  • The push method is used to add one or more elements to the end of the array and return the length of the array after adding new elements. Note that this method changes the original array.

    var a = [];
    a.push(1) // 1
    a.push('a') // 2
    a.push(true, {}) // 4
    console.log(a); //[1, 'a', true, {}]
    
  • The pop method deletes the last element of the array and returns it. Note that this method changes the original array

    var a = ['a', 'b', 'c'];
    a.pop() // 'c'
    console.log(a);// ['a', 'b']
    
  • slice method is used to extract part of the original array and return a new array. The original array remains unchanged.

    Its first parameter is the start position (starting from 0), and the second parameter is the end position (but the element of the position itself is not included). If the second parameter is omitted, it returns to the last member of the original array.

    var a = ['a', 'b', 'c'];
    a.pop() // 'c'
    console.log(a);// ['a', 'b']
    
  • The join method is used to splice array elements into strings with specified characters and return a string. The original array remains unchanged.

    var a = ['a','b','c','d','e'];
    console.log(a.join('-')) // 'a-b-c-d-e'
    
  • Returns a string representation of an array.

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

2.1. 2 comparison table of methods and attributes

Properties of the Array object

attributedescribe
length attributeReturns an integer value, which is 1 larger than the highest order element defined in the array and is the actual number of elements.

Method of Array object

methoddescribe
concat method (array)Returns a new array composed of two arrays.
entries methodReturns an iterator containing key / value pairs of an array.
every methodChecks whether the defined callback function returns {true for all elements in the array.
fill methodFills the array with the specified value.
filter methodCall the defined callback function on each element of the array and return the array for which the callback function returns the value of {true}.
findIndex methodReturns the index value of the first array element that meets the test conditions specified in the callback function.
forEach methodCall the defined callback function for each element in the array.
hasOwnProperty methodReturns a Boolean value indicating whether an object has a property with the specified name.
indexOf method (array)Returns the index of the first occurrence of a value in an array.
isPrototypeOf methodReturns a Boolean value indicating whether one object exists in the prototype chain of another object.
join methodReturns a String object formed by concatenating all elements of an array.
keys methodReturns an iterator containing the index value of an array.
lastIndexOf method (array)Returns the index of the last occurrence of the specified value in the array.
map methodCall the defined callback function on each element of the array and return the array containing the result.
pop methodRemoves the last element from the array and returns it.
propertyIsEnumerable methodReturns a Boolean value indicating whether the specified property is part of an object and enumerable.
push methodAppends a new element to an array and returns the new length of the array.
reduce methodA single result is accumulated by calling a defined callback function on all elements in the array. The return value of the callback function is the cumulative result and is provided as a parameter in the next call to the callback function.
reduceRight methodAccumulate individual results in descending order by calling the defined callback function on all elements in the array. The return value of the callback function is the cumulative result and is provided as a parameter in the next call to the callback function.
reverse methodReturns the Array object whose element order is reversed.
shift methodRemoves the first element from the array and returns it.
slice method (array)Returns a portion of an array.
some methodChecks whether the defined callback function returns {true for any element of the array.
sort methodReturns an Array object whose elements have been sorted.
splice methodRemove an element from an array, insert a new element at the position of the removed element if necessary, and return the removed element.
toLocaleString methodReturns a string that uses the current locale.
toString methodReturns a string representation of an array.
unshift methodInsert a new element at the beginning of the array.
valueOf methodGets a reference to an array.
values methodReturns an iterator containing the value of an array.

 

Topics: Javascript