Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the collection types of javascript and how to use them

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the javascript collection types and how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that you read this javascript collection types and how to use the article will have a harvest, let's take a look at it.

There are three types of collection: 1, map type, Map collection is stored in the key-value pair, keys can not be repeated, values can be repeated; 2, Set type, objects stored in Set are unordered, can not be repeated, objects in the collection are not sorted in a specific way; 3, List type, objects stored in List are ordered, repeatable, and its query speed.

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

There are three collection types for javascript: set (set), list (list), and map (mapping).

1. Map (key value pair, key unique, value is not unique):

Map is the structure of a set of key-value pairs with extremely fast search speed. Created by passing in an array of arrays. Add a new element by calling .set (key,value).

Var m = new Map ([['Michael', 95], [' Bob', 75], ['Tracy', 85]]); m.get (' Michael'); / / 95m.set ('Adam', 67); / / add a new key-value

For example, suppose you want to find the corresponding grade based on the name of the classmate. If you implement it in Array, you need two Array:

Var names = ['Michael',' Bob', 'Tracy']; var scores = [95,75,85]

Given a name, to find the corresponding score, you must first find the corresponding location in names, and then extract the corresponding score from scores. The longer the Array, the longer it takes.

If you implement it in Map, you only need a "name"-"score" comparison table to look up the score directly according to the name. No matter how big the table is, the search speed will not slow down.

Write a Map in JavaScript as follows:

Var m = new Map ([['Michael', 95], [' Bob', 75], ['Tracy', 85]]); m.get (' Michael'); / / 95

Initializing Map requires a two-dimensional array, or initializing an empty Map directly.

Map has the following methods:

Var m = new Map (); / / empty Mapm.set ('Adam', 67); / / add new key-valuem.set (' Bob', 59); m.has ('Adam'); / / whether there is key' Adam': truem.get ('Adam'); / / 67m.delete (' Adam'); / / delete key 'Adam'm.get (' Adam'); / / undefined

Since a key can only correspond to one value, if you put a value into a key multiple times, the following value will flush out the previous value:

Var m = new Map (); m.set ('Adam', 67); m.set (' Adam', 88); m.get ('Adam'); / / 88

1) attributes and methods

Definition: a collection of key / value pairs.

Syntax: mapObj = new Map ()

Note: the keys and values in the collection can be of any type. If you add a value to the collection using an existing key, the new value replaces the old value.

Map object attribute description constructor specifies the function to create the mapping Prototype-prototype returns the reference to the prototype the constructor returns the number of elements in the mapping Map object method description clear removes all elements from the map delete removes the specified element from the mapping forEach performs a specified operation on each element in the mapping get returns the specified element has in the mapping if the mapping contains the specified element Returns truetoString returns the string representation of the mapping set adds a new element to the mapping valueOf returns the original value of the specified object / / how to add members to the Map, and then retrieves them var m = new Map () M.set (1, "black"); m.set (2, "red"); m.set ("colors", 2); m.set ({x key 1}, 3); m.forEach (function (item, key, mapObj) {[xss_clean] (item.toString () + ");}); [xss_clean] ("); [xss_clean] (m.get (2)); / / Output:// black// red// 2 / 3) / red

2. Set (unordered, non-repeatable):

Set, like Map, is a collection of key, but does not store value. Because key cannot be repeated, there is no duplicate key in Set.

The objects stored in Set are unordered and cannot be repeated. Objects in the collection are not sorted in a specific way, but are simply added to the collection.

1) create a Set

Set itself is a constructor that is called to generate Set data structures.

Keyword identifier = new Set ()

Example

Var S1 = new Set (); / / empty Setvar S2 = new Set ([1,2,3]); / / including 1,2,3

The Set function can take an array (or an array-like object) as an argument for data initialization.

Let I = new Set ([1,2,3,4,4]); / / you will get set {1,2,3,4,}

Note: if the value given during initialization is duplicated, it will be removed automatically. Collections do not have a literal declaration.

2) attributes of Set

There is only one commonly used property: size returns the total number of members of the Set instance.

Let s = new Set ([1,2,3]); console.log (s.size); / / 3

3) the method of Set

The methods of Set instances fall into two main categories: operation methods (for data manipulation) and traversal methods (for traversing data).

Method of operation:

Add (value) adds data and returns a new Set structure

Delete (value) deletes the data and returns a Boolean value indicating whether the deletion is successful

Has (value) checks to see if some data exists and returns a Boolean value

Clear () clears all data and returns no value

Let set = new Set ([1,2,3,4,4]); / / add data 5let addSet = set.add (5); console.log (addSet); / / Set (5) {1,2,3,4,5} / / Delete data 4slet delSet = set.delete (4); console.log (delSet); / / true// to see if there is data 4let hasSet = set.has (4); console.log (hasSet) / / false// clears all data set.clear (); console.log (set); / / Set (0) {}

Traversal method:

Set provides three traversal generator functions and a traversal method.

Keys () returns an ergodic with a key name

Values () returns an ergodic with a key value

Entries () returns an ergodic of a key-value pair

ForEach () uses the callback function to iterate through each member

Let color = new Set (["red", "green", "blue"]); for (let item of color.keys ()) {console.log (item);} / / red// green// bluefor (let item of color.values ()) {console.log (item);} / / red// green// bluefor (let item of color.entries ()) {console.log (item) } / / ["red", "red"] / / ["green", "green"] / / ["blue", "blue"] color.forEach ((item) = > {console.log (item)}) / / red// green// blue

3. List (orderly and repeatable):

A list is an ordered set of data, and the data items in each list are called elements.

The objects stored in List are ordered and repeatable. List focuses on indexes, has a series of index-related methods, and is fast to query. Because the insertion or deletion of data into the list collection will be accompanied by the movement of subsequent data, the speed of all insert and delete data is slow.

The list has attributes that describe the location of the element, and the list has front and back (front and end).

Use the next () method to move from the current element to the next element, the next () method to move from the current element to the next element, the prev () method to move to the previous element of the current element, and the moveTo (n) method to move directly to the specified location

1) the method of List:

The properties defined are:

ListSize: the number of elements in the list

Pos: the current location of the list

The methods that are defined are:

GetElement (): returns the element of the current position

Insert (): insert a new element after an existing element

Append (): add a new element to the end of the list

Remove (): removes an element from the list

Length (): returns the number of elements in the list

Clear (): clear the list

Contains (): determines whether the element exists in the list

Move the element:

Front (): moves the current position of the list to the first element

End (): moves the current position of the list to the last element

Prev (): moves the current position back one bit

Next (): moves the current position forward one bit

CurrPos (): returns the current position of the list

MoveTo (): moves the current location to the specified location

2) implementation of List

Use arrays to implement a list and initialize property values

Function List () {this.listSize = 0; / / number of record list elements this.pos = 0; / / location of record list this.dataStore = []; / / Storage list element}

Append (element) add element

The method of adding a new element to the end of a list is the same as pressing the stack

Add 1 to the listSize of the number of record elements to get the location where the element is stored, and then add the element to this location

Function append (element) {/ / add 1 to the length of the list, and then populate the element to the new location this.dataStore [this.listSize++] = element;}

Find (element) find elements

First iterate through the list. If the element you want to find exists in the list, return the location of the element. If it is not found, return-1.

Function find (element) {/ / traversal list for (let I = 0; I

< this.dataStore.length; ++i) { //判断列表中是否有该元素,存在则返回索引i if (this.dataStore[i] == element) { return i; }; }; //不存在返回-1 return -1;}; remove(element) 删除元素 先调用find方法,查找元素的位置,如果存在返回true,不存在则会返回false; 如果存在,使用js数组操作方法splice删除当前元素,splice方法接收两个参数,即要删除的元素的索引和要删除的个数; 删除元素后,要将列表的长度减1; function remove(element) { //调用定义的find方法查找元素 let fountAt = this.find(element); //元素存在 if (fountAt >

-1) {/ / delete the value corresponding to the index this.dataStore.splice (fountAt, 1); / / one element is missing from the list, minus 1-- this.listSize; / / returned true return true;} successfully; / / return false return false;} if no element is found

Length () query how many elements are in the list

This method returns the elements in the list and directly returns the value of listSize

Function length () {return this.listSize;}

Insert (element, after) inserts elements into the list

This method inserts the target element after the specified element, which receives two parameters, namely, the target element element and the specified element after

Implementation: first use the defined find method to find the location of the after, and then use the splice method to insert the target element in the next bit of the location

The splice method passes in three parameters, the location of the target value, the number to be deleted, and the value to be inserted (the second parameter is 0, which means 0 elements are deleted)

True is returned if the operation is successful, and false is returned if the specified element is not found

Function insert (element, after) {let insertPos = this.find (after); if (insertPos >-1) {this.dataStore.splice (insertPos + 1,0, element); + + this.listSize; return true;}; return false;}

Clear () empties the list

Delete list, initialize data

Function clear () {delete this.dataStore; this.dataStore = []; this.listSize = 0; this.pos = 0;}

Contains (element) determines whether the element exists in the list

Similar to the find method, you can also directly use the find method to find and return true. There is no return false.

Function contains (element) {for (let I = 0; I)

< this.dataStore.length; ++i) { if (this.dataStore[i] == element) { return true; }; }; return false;}; 迭代器:移动列表中的元素 创建手动迭代列表的一些方法,可以不用关心数据的内部存储方法,以实现对列表的遍历。 //移动到最前面function front() { this.pos = 0;};//移动到最后面function end() { this.pos = this.listSize - 1;};//往后移一位function prev() { if (this.pos >

0) {--this.pos;};}; / / move forward one bit function next () {if (this.pos < this.listSize-1) {+ + this.pos;};}; / / return the current position of the list function currPos () {return this.pos;}; / / move to the specified location function moveTo (position) {this.pos = position;} / / returns the location of the current element function getElement () {return this.dataStore [this.pos];}; this is the end of the article on "what are the collection types of javascript and how to use them?" Thank you for reading! I believe you all have a certain understanding of the knowledge of "what are the collection types of javascript and how to use them". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report