"JS learning notes" JS array

Posted by codrgii on Wed, 05 Jan 2022 09:40:54 +0100

1, What is an array

Array, as its name implies: the type used to store a set of related values.

Array can easily sum a group of values, calculate the average value, traverse item by item and so on.

var scoreArr = [87, 89, 93, 71, 100, 68, 94, 88];

Array names are used to end with Arr.

2, Definition of array

2.1 square bracket definition

var arr = ['A', 'B', 'C', 'D'];

2.2 new definition method

var arr = new Array('A', 'B', 'C', 'D');
var arr = new Array(4);
// Define an array with a length of 4, but these 4 items are undefined

3, Access array items

Each item of the array has a subscript, which starts from 0!

You can access any item of the array in the form of array name [subscript].

4, Subscript out of bounds

JS stipulates that accessing items that do not exist in the array will return undefined and no error will be reported!

5, Length of array

The length property of the array indicates its length.

var arr = ['A', 'B', 'C', 'D'];
console.log(arr.length);	// 4

The subscript of the last item of the array is the length of the array minus 1.

6, Change array entry

1. Access array items
2. Change array value

If the changed array item exceeds length-1, the item is created.

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

7, Traversal of array

The biggest advantage of array is that it is easy to traverse.

var arr = [1, 2, 3, 4];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

8, Detection of array type

The array is detected with typeof, and the result is object.

Array. The isarray () method can be used to detect an array and return a Boolean value.

isArray() is not compatible with IE678, so the "duck type discrimination" detection method will also be introduced in later courses.

Array.isArray([1, 2, 3]);		// true
Array.isArray([]);				// true

9, Common methods of array

9.1 header and footer operation of array

methodfunction
push()Insert new item at the end
pop()Delete at tail

9.1.1 push() method

The push() method is used to push a new item at the end of the array, and the parameter is the item to be pushed.

If you want to push multiple items, you can separate them with commas.

After the push() method is called, the array will change immediately without assignment.

var arr = [22, 33, 44, 55];
arr.push(66);
arr.push(77, 88, 99);
console.log(arr);
// [22, 33, 44, 55, 66, 77, 88, 99]

9.1.2 pop() method

In contrast to the push() method, the pop() method is used to delete the last item in the array.

There are no parameters in (). The last item will pop up by default.

pop() returns the value of the last item by default.

var arr = [22, 33, 44, 55];
var item =  arr.pop();
console.log(arr);	// [22, 33, 44]
console.log(item);	// 55

9.1.3 unshift() method

The unshift() method is used to insert a new item at the head of the array, and the parameter is the item to be inserted.

If you want to insert multiple items, you can separate them with commas.

After calling the unshift() method, the array will change immediately without assignment.

9.1.4 shift() method

In contrast to the unshift() method, the shift() method is used to delete the first entry in the array.

There are no parameters in (). The first item pops up by default.

shift() returns the value of the first item by default.

9.2 splice() method

The splice() method replaces the specified item in the array.

Because splice() can realize many functions, it is also called "multi-functional method" of JS.

• Replacement item
var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
// Start with the item with subscript 3 and replace 2 items in succession.
arr.splice(3, 2, 'X', 'Y', 'Z');
console.log(arr);
// ['A', 'B', 'C', 'X', 'Y', 'Z', 'F', 'G']
• Insert item
var arr = ['A', 'B', 'C', 'D'];
// Starting from the item with subscript 2, replace 0 items continuously, that is, insert at .
arr.splice(2, 0, 'X', 'Y', 'Z');
console.log(arr);
// ['A', 'B', 'X', 'Y', 'Z', 'C', 'D']
• Delete item
var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
// Starting from the item with subscript 2, replace 4 items continuously (replace with empty, i.e. delete).
arr.splice(2, 4);
console.log(arr);
// ['A', 'B', 'G']

The splice() method returns the replaced / deleted items as an array.

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
// Start with the item with subscript 3 and replace 2 items in succession.
var item = arr.splice(3, 2, 'X', 'Y', 'Z');
console.log(arr);
// ['A', 'B', 'C', 'X', 'Y', 'Z', 'F', 'G']
console.log(item);
// ['D', 'E']

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
// Starting from the item with subscript 2, replace 4 items continuously (replace with empty, i.e. delete).
var item = arr.splice(2, 4);
console.log(arr);
// ['A', 'B', 'G']
console.log(item);
// ['C', 'D', 'E', 'F']

9.3 slice() method

The slice() method is used to get the subarray, similar to the slice() method in a string.

The subarray intercepted by slice(a, b) starts with the item with subscript A and ends with subscript b (excluding the item with subscript b).

slice(a, b) method does not change the original array.

slice() if it does not provide the second parameter, it means that all subsequent items are extracted as a subarray starting from the specified item.

The parameter of slice() method is allowed to be negative, indicating the penultimate item of the array (remember not to include the last item).

var arr = ['A', 'B', 'C', 'D', 'E', 'F'];
var childArr1 = arr.slice(2, 5);
var childArr2 = arr.slice(2);
var childArr3 = arr.slice(2, -1);
console.log(arr);			// ['A', 'B', 'C', 'D', 'E', 'F']
console.log(childArr1);		// ['C', 'D', 'E']
console.log(childArr2);		// ['C', 'D', 'E', 'F']
console.log(childArr3);		// ['C', 'D', 'E']

9.4 join() and split() methods

The join() method of the array can convert the array to a string.

The split() method of a string can convert a string into an array.

• The parameter of join() indicates what character is used as the connector. If it is left blank, it is separated by commas by default, just like calling the toString() method.
• The parameter of split() indicates the character to split the string. Generally, it cannot be left blank.
[22, 33, 44, 55].join();		// "22,33,44,55"
[22, 33, 44, 55].toString();	// "22,33,44,55"
[22, 33, 44, 55].join(',');		// "22,33,44,55"
[22, 33, 44, 55].join('-');		// "22-33-44-55"
[22, 33, 44, 55].join('~');		// "22~33~44~55"
'abcdefg'.split();				// ["abcdefg"]
'abcdefg'.split('');			// ["a", "b", "c", "d", "e", "f", "g"]
'a-b-c-d-e-f-g'.split('');		// ["a", "-", "b", "-", "c", "-", "d", "-", "e", "-", "f", "-", "g"]
'a-b-c-d-e-f-g'.split('-');		// ["a", "b", "c", "d", "e", "f", "g"]

9.5 string and array more dependencies

A character string can also be accessed in the form of [subscript], which is equivalent to the charAt() method.

When traversing the characters in the string, you don't need to turn them into an array, just use [subscript].

Some algorithm problems of string will be solved by array!

'I love the front end';			// "I"
'I love the front end';			// "Love"
'I love the front end'.charAt(0);	// "I"
var str = 'I love the front end';
for (var i = 0; i < str.length; i++) {
console.log(str[i]);
}

9.6 concat() method

The concat() method can combine and join multiple arrays (in the form of return values).

The concat() method does not change the original array.

var arr1 = [1, 2, 3, 4];
var arr2 = [5, 6, 7, 8];
var arr3 = [9, 10, 11];
var arr = arr1.concat(arr2, arr3);
console.log(arr);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

9.7 reverse() method

The reverse() method is used to reverse the order of all items in an array.

var arr = ['A', 'B', 'C', 'D'];
arr.reverse();
console.log(arr);	// ["D", "C", "B", "A"]

[a small case]

The string 'ABCDEFG' is in reverse order.

'ABCDEFG'.split('').reverse().join('');
// "GFEDCBA"

9.8 indexOf() and includes() methods

The function of indexOf() method is to search the element in the array and return its location. If the element does not exist, it returns - 1.

The function of the includes() method is to judge whether an array contains a specified value and return a Boolean value.

['A', 'B', 'C', 'D'].indexOf('C');	// 2
['A', 'B', 'C', 'D'].indexOf('D');	// 3
['A', 'B', 'C', 'D'].indexOf('X');	// -1
['A', 'B', 'B', 'B'].indexOf('B');	// 1
['A', 'B', 'C', 'D'].includes('D');	// true
['A', 'B', 'C', 'D'].includes('X');	// false

Note: the judgment criteria of indexOf() and includes() methods are = = = all equal!

[11, 22, 33].includes('22');	// false
[11, 22, 33].indexOf('22');		// -1

9.9 sort() method

Array has sort() method, which can be used for array sorting, but it involves the related knowledge of functions, which will be introduced in the function class.

In addition to the built-in sorting method, there are some sorting algorithms: bubble sorting and quick sorting, which will be introduced later.

9.10 enhancement of arrays in ES6

Array adds many new methods in ES6, which will be introduced in ES6 related courses.

9.11 array de duplication and random samples

[array de duplication]

Title: remove duplicates from the array.

Idea: prepare an empty result array and traverse the original array. If the traversed items are not in the result array, push the result array.

var arr = [1, 1, 1, 2, 2, 3, 3, 3, 2, 1];
var resultArr = [];
for (var i = 0; i < arr.length; i++) {
if (!resultArr.includes(arr[i])) {
resultArr.push(arr[i]);
}
}
console.log(resultArr);

[random sample]

Title: Please randomly take 3 items from the original array.

Idea: prepare an empty result array, traverse the original array, randomly select one item, push it into the result array, and delete this item in the original array.

var arr = [3, 6, 10, 5, 8, 9];
var resultArr = [];
for (var i = 0; i < 3; i++) {
var n = parseInt(Math.random() * arr.length);
resultArr.push(arr[n]);
arr.splice(n, 1);
}
console.log(resultArr);

9.12 bubble sorting

Bubble sort is a famous sort algorithm and the most basic exchange sort.

The core idea of bubble sorting: carry out pairwise comparison of multiple items one at a time, and arrange the largest elements in a good position each time, just like bubbles floating in the water.

Time complexity: O(n) ²) var arr = [9, 5, 6, 8, 2, 7, 3, 4, 1];
var temp;
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
console.log(arr);

10, Two dimensional array

Two dimensional array: an array with an array as an array element, that is, "array of arrays".

Two dimensional arrays can be regarded as "matrices".

Matrix: matrix

var matrix = [
[11, 33, 55],
[22, 33, 44],
[36, 49, 52],
[56, 10, 23]
];

// 2D array length
console.log(matrix.length);		// 4
console.log(matrix.length);	// 3

// Traversing a two-dimensional array
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}

11, Basic type value and reference type value

When var a = b variable passes valueWhen compared with = =
Basic type valueGenerate a new copy in memoryCompare values for equality
Reference type valueInstead of generating a new copy in memory, let the new variable point to the same objectCompare whether the memory addresses are equal, that is, compare whether they are the same object
var a = 3;
var b = a;
a++;
console.log(a);		// 4
consloe.log(b);		// 3
var arr1 = [1, 2, 3, 4];
var arr2 = arr1;
arr1.push(5);
console.log(arr1);	// [1, 2, 3, 4, 5]
console.log(arr2);	// [1, 2, 3, 4, 5]
• Basic types: number, boolean, string, undefined, null
• Reference types: array, object, function, regexp

[memory]  [difference in equality judgment]

• When judging the equality of basic types, it will compare whether the "values" are equal
• When judging the equality of reference types, it will compare whether the "address" is equal, that is, it will compare whether it is the same thing in memory
3 == 3;		// true
[1, 2, 3] == [1, 2, 3];	// false
[] == [];	// false
// To judge an empty array, please judge length == 0

var arr = [1, 2, 3];
arr == arr;		// true
var arr2 = arr;
arr == arr2;	// true
arr === arr2;	// true

12, Deep and shallow cloning

Deep cloning and shallow cloning require handwritten code implementation, rather than simply calling functions.

The syntax of using arr1 = arr2 does not clone arrays.

Shallow cloning: only the first layer of the array is cloned. If it is a multidimensional array or the items in the array are values of other reference types, no other layers are cloned.

Deep cloning: to clone all layers of an array, you need to use recursive technology, which will be introduced in later courses.

[shallow cloning]

Core idea: "broken lotus roots"

var arr = [1, 2, 3, 4, [5, 6, 7]];
var resultArr = [];
for (var i = 0; i < arr.length; i++) {
resultArr.push(arr[i]);
}
console.log(resultArr);		// [1, 2, 3, 4, [5, 6, 7]]
console.log(resultArr == arr);  		// false
console.log(resultArr == arr);	// true

Topics: Javascript Front-end