Common collection reference types include Object, Array, Map, Set, etc
Object
Most reference values are of the Object type used.
// Literal definition let obj = { // Store values of any type. val: 10, obj: {}, func() { } }; // Value console.log(obj.val); console.log(obj["val"]);
Array
Arrays in JavaScript are dynamic and can store arbitrary types of values and an ordered set of data.
When the array length changes, the original array will be destroyed and a new array will be created. The maximum length of the array does not exceed 4294967295.
let arr = ["Hello"]; // arr.length = 10; let arr2 = new Array("Hello"); // let arr2 = new Array(10); // Index modification, access, increase arr[0] = "other"; console.log(arr[0]); arr[1] = ""
Static method
- The from() class converts an array into an array.
- of() converts a set of parameters into an array.
- isArray() detects whether it is an array.
Prototype method
-
fill() specifies a range for batch copying
-
copyWithin() specifies the range to copy part of the contents of the array.
-
Conversion method:
- toString(),valueOf(),toLocaleString()
- join() concatenates each item of the array according to the specified delimiter.
-
Add and delete from beginning to end to change the original array
- The tail of push() increases and returns the length of the array.
- pop() removes the tail and returns the removed item.
- shift() removes the header and returns the removed item.
- unshift() increases the header and returns the length of the array.
-
The sorting method changes the original array
- reverse() reverses the array.
- sort() sorts by collation.
-
Operation method
- concat() returns the spliced array.
- slice() returns an array of items in the specified range.
- splice() is used to modify, delete and insert arrays, and returns an array composed of deleted items. Will change the original array.
-
Search and location methods
- Strict Equality: indexOf(), lastIndexOf(), includes()
- Assertion function: find() returns the matching item, and findIndex() returns the subscript of the matching item.
-
Iterative method
- every() matches every item. Returns a Boolean value.
- filter() filters the array and returns.
- forEach() traverses the array and has no return value.
- map() traverses the array and returns the function composed of the result of each function call.
- There is a match for some(). Returns a Boolean value.
-
Merging method
- reduce() returns a final result after traversing the array+ reduceRight()
-
Expand item
- flat() expands each item by depth.
- flatMap() iterates over each element and compresses it into an array.
-
generator iterator
- keys() returns the iterator of the subscript.
- values() returns an iterator of the value.
- entries() returns the iterator of [subscript, value].
TypedArray training array
Stereotyped array is a new structure added by ECMAScript to improve the efficiency of transmitting data from the native library.
JavaScript does not have TypedArray, but is a special array containing numeric types.
Make full use of 3D graphics API and GPU acceleration to render complex graphics on < canvas > elements.
ArrayBuffer
ArrayBuffer is the basic unit for all training array and view references.
ArrayBuffer is a common JavaScript constructor that can be used to allocate a specific amount of byte space in memory.
const buf1 = new ArrayBuffer(16); // Once created, you can no longer resize. const buf2 = buf1.slice(4, 12); // slice can specify a complex range of values. console.log(buf2.byteLength); // byteLength byte length
You cannot directly operate the contents of ArrayBuffer. You need to operate through type array objects or DataView objects. They will represent the data in the buffer in specific formats and read and write the contents of the buffer through these formats.
DataView
DataView is specially designed for file I/O and network I/O. its API supports high control over buffered data, and its performance is worse than other types of frontal views.
DataView has no preset for buffer and cannot be iterated.
const dataBuf = new ArrayBuffer(256); const dataView = new DataView(dataBuf); // Using a buffer, you can set its usage range. console.log(dataView.byteOffset); // Offset console.log(dataView.byteLength); // How long is the buffer used console.log(dataView.buffer === dataBuf); // Set Int8 -128~127 dataView.setInt8(0, 128); console.log(dataView.getInt8(0)) // -128 // Set Uint8 0~255 dataView.setUint8(1, 256); console.log(dataView.getUint8(1)) // 0
Training array
The training array is also an ArrayBuffer view. Compared with DataView, stereotyped array provides more API s and high performance.
The design purpose is to exchange binary data with WebGL and other native libraries. The JavaScript engine can heavily optimize arithmetic operations, bitwise operations and other operations on stereotyped arrays.
How to create a training array:
- Read existing cache.
- Use own cache.
- Fill the iteratable structure.
- Fills a training array of any type.
- Static functions from() and of()
let typeArray = new Int32Array(10); console.log(typeArray.BYTES_PER_ELEMENT); // The size of each element. console.log(typeArray.length); // length console.log(typeArray.byteLength); // byteLength = length * BYTES_PER_ELEMENT
Compared with ordinary functions, stereotyped arrays are used in the same way except that methods that may change the length of the original array (pop|push|shift|unshift|splice) and concat methods cannot be used.
The stereotyped array provides two methods, set and subarray, to copy the array outward or inward.
let typeArray2 = new Int32Array(10); console.log(typeArray2); typeArray2.set(new Int32Array([1, 2, 3, 4]), 2); // Modify the contents similar to array splice console.log(typeArray2); console.log(typeArray2.subarray(3, 9)); // Copies items in the specified range
Map
Map is a collection type. Similar to Object. Map can use any type as a key.
Prototype method properties
- Number of size key value pairs.
- set() adds or modifies the value corresponding to the specified key.
- get() gets the value corresponding to the key.
- has() determines whether the corresponding key is included.
- forEach() traversal.
- delete() deletes the key value pair of the specified key.
- clear() clears all key value pairs.
- keys(), values(), and entries() get the corresponding iterators.
let obj = {}; let map = new Map([[obj, obj]]); // Initialization: an array composed of no value or [key,val]. let key = function () { return "key"; }; map.set(obj, {a: 10}); // change a value map.set(key, key); // New value added let getKey = map.get(key); // Get value does not exist, return undefined console.log(map.has(key)); // Does it exist console.log(getKey()); // The corresponding iterator function is used for for of traversal console.log(map.keys()); console.log(map.values()); console.log(map.entries()); console.log(map.size); // Number of key value pairs map.delete(obj); // delete map.clear(); // empty console.log(map.size);
Differences between Object and Map
It doesn't make much difference for web development. The difference is mainly reflected in performance and memory.
- Memory usage: Map stores about 50% more key value pairs than Object.
- Insertion performance: inserting a new key map is slightly faster. Map performance is better when there are a large number of insert operations.
- Search speed: the performance difference between the two is very small, but in a large number of search operations, Object is better.
- Deletion performance: Object deletion is not recommended. Generally, the value is set to null or undefined. For the delete operation, the delete operation of Map is better.
WeakMap
WeakMap is a weak set type. JavaScript garbage collection is a way to treat keys in weak types.
WeakMap can only use Object or types inherited from Object.
Prototype method
- set() adds or modifies the value corresponding to the specified key.
- get() gets the value corresponding to the key.
- has() determines whether the corresponding key is included.
- delete(). Deletes the key value pair for the specified key.
The WeakMap instance is of weak type, unable to get the methods related to size and iterator, and there is no clear() method.
WeakMap adaptation scenario:
- Private variables: private variables are stored in weak mappings, object instances are keys, and private member dictionaries are values. This is not a real private variable.
- DOM node metadata: the WeakMap instance does not hinder garbage collection and is suitable for saving associated metadata.
Set
Set is a collection type. Set is like an enhanced map (key = = = value). The values of members are unique and there are no duplicate values.
Prototype method properties
- Number of size value pairs.
- add() adds a value.
- has() determines whether the corresponding key is included.
- forEach() traversal.
- delete() deletes the specified value.
- clear() clears all values.
- keys(), values(), and entries() get the corresponding iterators.
let set = new Set(); let obj = { name: 10 } console.log(set.size); set.add(obj); console.log(set.size); console.log(set.has(obj)); set.forEach((value, value2, set1) => { console.log(value) }) console.log(set.values()) console.log(set.entries()) console.log(set.keys()) set.delete(obj); set.clear();
Set can be used for array de duplication.
WeakSet
WeakSet is a weak set type. JavaScript garbage collection is a way to treat weak types.
A WeakSet can only use Object or types that inherit from Object.
Prototype method
- add() adds a value.
- has() determines whether the corresponding value is included.
- delete(). Deletes the specified value.
The WeakSet instance is of weak type. It cannot get the methods related to size and iterator, and there is no clear() method.
WeakSet adaptation scenario:
A WeakSet can be used to label objects. The corresponding logic is completed by judging the state of the secondary object.
Iterating over extended operations
Array, training array, Map and Set all define default iterators (for-of loops can be used).
The extension operator (...) is used for shallow copying of arrays and iteratable objects.