14000 word notes in Chapter 3 of learning JavaScript data structures and algorithms

preface

This paper includes array operation method, new array function in ES6, JS matrix, typed array, etc;

Is the catalogue clear? It's convenient to check something? I've tried my best to improve the catalogue for future reference

The front is the basic part. If you're not Xiaobai, I think

1, Create & & initialize array

Create and initialize arrays using JavaScript declarations;

Use the new keyword to simply declare and initialize an array.
The advantage of this method is that the length of the array can be determined directly at the time of declaration:

daysOfweek = new Array(Array length, numeric);
daysOfweek1 = new Array(7);

Or use square brackets directly:

let daysOfweek = [];
let daysOfweek1 = ['one', 'two', 'three'];

get array length:

console.log(Array name.length);

2, Operation array

Add element at end

Directly assign the array element to be added to the last bit of the array, but this method can only add one element at a time:

let array = ["one", "two", "three"];
array[array.length] = New array element;
console.log(array);

The method we use more in actual combat is push(), which is a method dedicated to processing arrays:

let array = ["one", "two", "three"];
array.push(Element to add 1, Element to add 2, ...);
array.push(array2[3]);

Multiple elements can be added to the end of the array at one time

Add element at beginning

Add a new array element directly to the beginning of the array. In practice, the unshift method is generally used:

let numbers = [3, 4, 55];
numbers.unshift(-2);
unmbers.unshift(-2, 3);
console.log(numbers);

Delete elements from the end of the array

Use the pop() method to delete elements from the array from the end:
The book did not elaborate on this method, only gave an example, so I had to run and try,

let numbers = [1, 2, 3, 4, 5];
numbers.pop();
console.log(numbers);


The pop() method only removes the last element, and it's useless to give parameters

Delete elements from the beginning of the array

for(let i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i + 1];
}

This is equivalent to moving all array elements to the left by one unit when the array serial number remains unchanged,
However, in this case, when the array is output, it will be found that the length of the array is still unchanged, which means that the value of one element in the array must be undefined:

As you can see, we just overwrite the value of the first bit of the array with the second bit, and the first bit is not deleted

However, in actual combat, we generally use the shift method:

let num = [1, 2, 3];
numbers.shift();

This method will directly reduce the length of the array

Add or remove elements anywhere in the array

Delete and add operations can be completed using splice();
Use the splice() method to complete the deletion operation by specifying the starting position and the number of deletions;

//Note: delete from left to right;
numbers.splice(Start serial number, Delete quantity);

Use the splice() method to complete the addition by specifying the starting position and passing in the element to be added:

//To add, please pass 0 for the second parameter;
number.splice(Start serial number, Delete quantity, Element 1, Element 2, Element 3, ...)

Can you see that the second parameter is still valid?
I only intend to add elements. You can delete them. I generously allow you to delete 0

3, Two dimensional multidimensional array

Matrix refers to the structure of an array including a two-dimensional array;

JavaScript only supports one-dimensional arrays and does not support matrices, but the following array nesting method can be used to implement matrices

Building 2D arrays

The one-dimensional array is regarded as a pipeline, and the array elements are regarded as commodities on the pipeline, so the two-dimensional array is stacked high in groups on the pipeline
Products:

Like this:

     ︹  ︹     ︹
     6   4      3
     3   5      9
     2   1      0
[ 3, ︺, ︺, 5, ︺, 6 ]

We have made a dimension leap, but we certainly can't write such a pipeline directly in the code, so we have to write it as follows:

[
3, 
[6, 3, 2],
[4, 5, 1],
5,
[3, 9, 0],
6,
]

Iterative 2D array

Double layer for iteration is used. Similarly, three-layer for iteration can be used for 3D arrays:

function printMatrix(myMatrix) {
  for(let i = 0; i < myMatrix.length; i++) {
    for(let j = 0; j < myMatrix[i].length; j++) {
      console.log(myMatrix[i][j]);
    }
  }
}

To get an element, you can directly use the following methods:
array[2][1];

4, JavaScript array method reference

methodexplain
concatJoin two or more arrays
foreachExecutes a function on each element in the array without a return value
everyExecute the function for each element in the array. If the execution of each element returns true,every() returns true;
filterExecute a function on each element in the array to return an array of all elements that return true when executed
mapExecute the function on each element in the array and return the array composed of all execution results
someExecute a function on each element in the array. As long as one element returns true,some() returns true
joinLinks all array elements into a string
indexOfReturns the index number of the first array element found equal to the given parameter
lastIndexOfReturns the one with the largest index number among all the array elements found equal to the given parameter, that is, the rightmost one among all the elements equal to the parameter
reverseInvert the order of array elements without changing the index numbers
sliceBased on the passed in index value, the elements within the index range will be returned as a new array
sortSort the array in alphabetical order. You can pass in [function specifying sorting method] as a parameter
toStringConverts an array to a string and returns
valueOfConverts an array to a string and returns it, similar to toSting

Some of these methods are very useful in functional programming;
I don't remember much about these. I can find them all

Array reverse sort: reverse()

Using the reverse() method on an array can obtain the reverse order form of an array. There's nothing to say,
However, the book also conducted a sort sort after using reverse() on the array. I checked the characteristics of sort first. If no parameters were passed when calling the sort() method, the elements in the array are sorted alphabetically (in the order of abcde);
But the example given in the book is a number array. Is that right?

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.reverse();
console.log(numbers);
numbers.sort()
console.log(numbers);


You can see that sorting with sort becomes messy again, because when sorting with sort(), it finds that the element is not a string, and it will try to convert the array element into a string for comparison
The default sorting method is not needed. Anyway, sort supports the introduction of compareFunction comparison function:

//The comparison function uses the arrow function: (a, b) = > {}

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.reverse();
numbers.sort();
console.log(numbers.sort((a, b) => a - b));

/
//sort() will interpret the size relationship between values according to the positive and negative of the returned value, which is equivalent to the following;

function compare() {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
return 0;
}
numbers.sort(compare);  //Pass the comparison function to sort as a parameter;

In this way, the purpose of resetting the reverse array is realized;

Value matching search: indexof & & lastIndexOf

Let's start with indexOf:
indexOf() returns the index of the first element that matches the parameter

console.log(numbers.indexOf(10)); //Returns 9 because the index of the value 10 is 9;
console.log(numbers.indexOf(100)); //Return - 1, because the array has no 100 at all;

If indexOf() can be found, the index number of the target array element will be output. If it cannot be found, it will output - 1;

Let's look at lastIndexOf():
lastIndexOf returns the index of the last element that matches the parameter
This means that if the search for an array produces multiple results that meet the conditions, it is not necessary to select the index number of the rightmost result as the return value;

numbers.push(10);
console.log(numbers.lastIndexOf(10));  //10
console.log(numbers.lastIndexOf(100));  //-1

The output array is a string: toString & & join

Both methods can convert an array into a string, but... There is still a little difference, that is
toString is to directly convert array elements into strings. To put it bluntly, it is to directly remove the outer brackets and directly expose the array elements and commas on the surface;

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(numbers.toString());

Then it becomes like this directly. Generally, it can't be used directly. You have to dismantle it and deal with it

Then there is join. The feature of this method is that you can specify what to connect after splitting each array element (it was not a comma in the array originally), and then after splitting, you can change it into "1QAQ2QAQ3QAQ4" or“ 1@2 @3 "and so on (this is actually a bit like the implode method in PHP)
Example:

const numberString = numbers.join("QAQ");
console.log(numbersString);

5, New functions of ES6 array

New methodexplain
@@iteratorReturns an iterator object containing array key value pairs. You can get the key value pairs of array elements through array synchronization calls
copyWithinCopies a series of elements in an array to the starting position specified by the same array
entriesReturns a @ @ iterator containing all key value pairs of the array (that is, key value pairs of index numbers and values)
keysReturns the @ @ iterator containing all the index numbers of the array (that is, the object containing the index numbers)
valuesReturns a @ @ iterator containing all the values in the array (that is, an object containing values)
includesQuickly check whether the array contains an element and return a Boolean value (this is the method from ECMAS7)
findYou can register a callback function, which will find an element from the array according to the conditions specified by the callback function. If the element is found, it will return
findIndexYou can register the callback function, which will find the element from the array according to the conditions specified by the callback function, and return its index number after finding it
fillPopulating an array with static values
fromCreate a new array from an existing array
ofCreates a new array based on the passed in parameters

Use for... of to traverse

For... Of executes a loop on iteratable objects (including Array, Map, Set, String, TypedArray, arguments, etc.) and executes statements for the values of each different attribute

let numbers = [3, 4, 7, 6];
for (const n of numbers) {
  console.log(n);
}

Formula:

let Array name = [Element 1, Element 2, Element 3, Element 4];
for (const key Name of Array name) {
  console.log(key Name);
}


You can see that in the for... of statement, the key is no longer the index number in for, but each array element;

@@iterator object

ES6 adds a @ @ iterator attribute to the Array class, which needs to be accessed through Symbol.iterator

let numbers = [1, 2, 3, 4, 5];
let iterator = numbers[Symbol.iterator]();
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);

Form repeated calls to next() to get the values in the array in turn:

Take out the key value pair of index number and value: entries()

In the above table, I mentioned the entries(), which returns the @ @ iterator. Containing all the key value pairs of the array

let aEntries = number.entries();
console.log(aEntries.next().value);
console.log(aEntries.next().value);
console.log(aEntries.next().value);

It's not good to write like this, so:
Example:

let array = [1, 2, 3];
aEntries = array.entries();
for(const n of aEntries) {
  console.log(n);
}

Formula:

let Array name = [Element 1, Element 2, Element 3];
Custom name = Array name.entries();
for(const key Name of Custom name) {
  console.log(key Name);
}


"When using data structures such as sets, dictionaries and hash tables, it is very useful to be able to fetch key value pairs"

Returns the object containing the index number: keys()

keys returns the @ @ iterator containing the array index number:
Example:

let array = [5, 4, 3, 2, 1];
const aKeys = array.keys();
for (let i = 0; i <= array.length;i++) {
  console.log(aKeys.next());
}

Formula:

let Array name = [Element 1, Element 2, Element 3, Element 4, Element 5];
const Custom name = Array name.keys();
for (let i = 0; i <= Array name.length;i++) {
  console.log(Custom name.next());
}


As for the latter done, it means "completed" in English. Put it here, that is, "completed or not",
If its value is false, it means that the array has not been iterated. You can see that when the array iterates to the end, done becomes true;
"Once there is no iteratable value, aKeys.next() will return an object whose value attribute is undedited and done attribute is true";

Returns the object containing the element value: values()

values() is the opposite of keys(). Instead of returning the index number, it returns the value of the element:

Example:

        let array = [5, 4, 3, 2, 1];
        const aKeys = array.values();
        for (let i = 0; i <= array.length; i++) {
            console.log(aKeys.next());
        }


The function of done is the same as keys(), which is used to determine whether the iteration of the current array is completed;

Find the value satisfying the function condition: find() & & findindex()

Both methods can receive callback functions to search for values that meet the conditions of the callback function and return these values
But there are some differences. Let's look at find():
find() returns the first value found that satisfies the function condition, focusing on the value
findIndex() returns the index number of the value that meets the condition (see the last line of the example);
Example:

//I've written the callback function outside here. It's OK to write the callback function like addEventListener
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

function multipleOf13(element) {
  return (element % 13 == 0);
}

console.log(numbers.find(multipleOf13)); //13
//Because there is only one array that satisfies the multiple of 13, the element value 13 is directly returned


console.log(numbers.findIndex(multipleOf13)); //12
//There is only one array that satisfies the multiple of 13, so the index number 12 of the value 13 is directly returned

Create a new array from an existing array: from()

The from() method creates a new array based on the existing array. For example, the numbers array to be copied is as follows:

let numbers = [5, 4, 3, 2, 1];
let numbers2 = Array.from(numbers);  
//from() uses the numbers array to generate a new array numbers2
console.log(numbers2);


However, it doesn't seem to make much sense to move it all directly. Most of the time, we need to filter to create a new array. The second parameter bit can come in handy. It supports passing in a function for filtering values:

let evens = Array.from(numbers, i => (i % 2 == 0));
//from() uses the numbers array to generate a new array evens;
//The filled Boolean value is determined according to the parity of the array elements;
console.log(evens);

Create a new array based on the passed in parameters: Array.of()

The Array.of method creates a new array based on the passed in parameters:

let numbers3 = Array.of(1);
let numbers4 = Array.of(1, 2, 3, 4, 5);
//Equivalent to let numbers4 = [1, 2, 3, 4, 5];
console.log(numbers3);
console.log(numbers4);

You can also pass in an array as a parameter! Remember the expansion operator mentioned earlier?

let numbers4 = [1, 2, 3, 4];
let numbersCopy = Array.of(...numbers4);
//Equivalent to let numbersCopy = Array.of(1, 2, 3, 4);
console.log(numbersCopy);

Fill the array with static values: fill()

fill() can fill your array with a certain value, or you can define the range with index numbers, so that all the elements of a range are a certain value;

Array name.fill(Values to populate, Start index number(Optional), End index number(Optional));

However, remember that the value corresponding to the start index number will be filled, but the value corresponding to the end index number will not be filled. For example, the index to be filled is only 3,4 when the start index number is 3 and the end index number is 5

let numbersCopy = Array.of(1, 2, 3, 4, 5, 6);
numbersCopy.fill(0, 2, 4);
console.log(numbersCopy);

One section of the variable array is the same as another: copyWithin()

The copyWithin() method copies (note that copying will not affect the replicator) a series of elements in the array to the specified position for replacement
Principle: copy the array elements on parameter 2 and its right to replace the corresponding number of array elements on parameter 1 and its right, and the array length will not be changed;

Next, I will change only one parameter, that is, the insertion point:

let copyArray = [1, 2, 3, 4, 5, 6];
copyArray.copyWithin(1, 4);  //Replace from index 1;
console.log(copyArray);  //(6) [1, 5, 6, 4, 5, 6]
let copyArray = [1, 2, 3, 4, 5, 6];
copyArray.copyWithin(0, 4);  //Replace from index 0;
console.log(copyArray);  //(6) [5, 6, 3, 4, 5, 6]

Formula:

let Array name = [Element 1, Element 2, Element 3, Element 4, Element 5, Element 6];
Array name.copyWithin(Replace starting point, Copy start point);  //Both points contain this point;

Detect whether an element exists in the array: includes()

Only yes or no can be detected, and the Boolean value is returned,;
Formula:

Array name.includes(Value to find);

Example:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(numbers.includes(15));
console.log(numbers.includes(3));

6, Typed array

A great feat of ES6 is to add the concept of type to JavaScript, a weakly typed language, and put it into practice. Type array is one of the crystallization of this technological revolution

"Type array is used to store single type data. Its syntax is let myArray = new TypedArray(length), where TypedArray needs to be replaced with one of the following tables."

However, I checked a lot of data. This thing is now related to the front end, but to be honest, I think it should be used in data processing, in the binary and byte levels. It's not useful to write a page and so on.
Moreover, it involves a wide range of knowledge. Here I will not go too deep to prevent misleading, but just talk about some related concepts and nouns (not written in these books)

Formula:

let [Custom name] = new [Array type]Array([Array length]);

Example:

let length = 5;
let int16 = new Int16Array(length);

Don't say so much. It says to look at the watch. Let me put the watch down first:

Type arrayData type
Int8Array8-bit binary complement integer
Uint8Array8-bit unsigned integer
Uint8ClampedArray8-bit unsigned integer (yes, correct)
Int16Array16 bit binary complement integer
Uint16Array16 bit unsigned integer
Int32Array32-bit binary complement integer
Uint32Array32-bit unsigned integer
Float32Array32-bit IEEE floating point number
Float64Array64 bit IEEE floating point number

Note that you can no longer use new Array() to fill type arrays:

//Error demonstration, which cannot be filled in. At most one parameter can be written in parentheses to specify length;
 let int16 = new Int16Array(5, 4, 3, 2, 1);
 

Instead, it should:

let f64a = new Float64Array(8);
f64a[0] = 10;
f64a[1] = 20;
f64a[2] = f64a[0] + f64a[1];
console.log(f64a);

"When using WebGL API, bit operation, file and image processing, type array can show its strength. It is no different from ordinary array. The array methods and functions learned in this chapter can be used for type array." in fact, this sentence from the book is wrong.

First, calling Array.isArray() in the type array will return false. In addition, not all methods that can be used for normal arrays can be supported by typed arrays (such as push and pop). I also tried it myself. It really can't be used. MDN especially emphasizes not to confuse ordinary arrays with typed arrays.

DataView:
Is an underlying interface that provides an API that can manipulate any data in ArrayBuffer. This is very helpful for scenarios where different types of data are operated. For example, typed array views run in the local byte order mode, and the byte order can be controlled by using DataView.

ArrayBuffer object:
It is used to represent the general-purpose, fixed length original binary storage space (or... Binary data buffer?). It is a byte array (called byte array in some languages) . instead of directly manipulating the contents of the ArrayBuffer, we need to operate through the type array or DataView object. I will give an example of these two methods. They will represent the data in the ArrayBuffer in a specific format to read and write the contents of the buffer.
As for the front end, as long as it is dealing with big data or wants to improve data processing performance, it must be ArrayBuffer

Look at the ArrayBuffer. The number in parentheses behind it refers to the number of bytes of storage space generated:

var buffer = new ArrayBuffer(16);

In order to read and write this paragraph, you need to create a view for it. The view will format the data in the binary storage space ArrayBuffer into a 32-bit signed integer array (for this example):
Here, the type array method is used for reading:

var int32View = new Int32Array(buffer);

Now you can access it in the form of ordinary array:

for (var i = 0; i < int32View.length; i++) {
  int32View[i] = i * 2;
}

perhaps
Read using DataView:

var buf = new ArrayBuffer(32);
//To create a DataView, you need to provide an ArrayBuffer instance as a parameter:
var dataView = new DataView(buf);
//Then read the first element in unsigned 8-bit integer format:
dataView.getUint8(0) // 0

In the unsigned 8-bit integer format, read the first element to get 0, because all bits in the ArrayBuffer object are 0 by default:

You can click here to see what the boss wrote

summary

I wrote 14000 words! 14000 words! It can't be put anywhere else. "I stayed up late for three days and got a ten thousand word long text" or "the most complete experience of ten thousand words". You see, I didn't get any boastful title? What positive energy it is! doge)
Do you think I've worked so hard (although I've written a lot of nonsense, it's also a word, and it's tiring to write nonsense, hey!), this reading note is longer than the original! It's very tiring!

So, give it a compliment, okay?

Tags: Javascript Algorithm data structure

Posted on Wed, 20 Oct 2021 17:55:11 -0400 by x2fusion