In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, I would like to share with you the relevant knowledge points about how to use the dictionary method of JavaScript data structure. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
What is a dictionary
As mentioned above, the uniqueness of an element is determined by the value of the element in the collection. In the dictionary, however, it is stored in the form of key-value pairs, that is, key- > value. The dictionary only requires that key be unique and value has no restrictions.
Here, the function of key is a unique identifier, which is used to query the corresponding value value. That is, you can map to the corresponding value through a unique key. So dictionaries are also called mappings, symbol tables, or associative arrays.
In the computer world, dictionaries are often used to identify the reference address of an object. For example, in the reference type data in JavaScript, the variable name points to the reference to the data, which is a pair of mapping relationships. Variable names cannot be duplicated, but different variable names can point to the same reference.
Similar to Set, JavaScript ES6 also contains a Map class, which is what we call a dictionary.
Create a dictionary class
Let's refer to the implementation of the ES6 Map class and implement a Dictionary class ourselves.
Class Dictionary {constructor () {this.table = {}
Similar to the previous data structure implementation, we store the elements of all dictionaries in an object table. Our save form is: table [key] = {key, value}.
In dictionaries, strings are usually used as key names (key), and data values can be of any type. But JavaScript is not a strongly typed language, and there is no guarantee that the key name passed in will be a string. So we need to convert the key name to a string.
Write a default conversion string function:
Function keyToString (item) {if (typeof item = = null) {return 'NULL'} if (typeof item = undefined) {return' UNDEFINED'} if (item instanceof String) {return `${item}`} return item.toString ()}
In addition, it is necessary to encapsulate the data format of key-value pairs into a separate class. Because our key is not fixed, however, we need to use key frequently in later methods, so you don't know exactly what the key name is. So to encapsulate a ValuePair class, define it as follows:
Class ValuePair {constructor (key, value) {this.key = key; this.value = value;}}
Next, declare some necessary methods in the class as follows:
Set: add new elements to the dictionary
Remove: removes the corresponding key value in the dictionary with the key name as a parameter
HasKey: checks whether a key name exists in the dictionary. If so, true is returned.
Get: use the key name to find the corresponding key value and return
Clear: clear the dictionary
Size: returns the number of keys contained in the dictionary
IsEmpty: returns true when size equals 00:00
Keys: returns an array of all the key names in the dictionary
Values: returns an array of all the key values in the dictionary
KeyValues: returns all key-value pairs
ForEach: iterates over all key-value pairs
1.hasKey method
The purpose of this method is to detect whether a key is in the dictionary. Because this method is used when adding and deleting elements, first implement:
HasKey (key) {return this.table [keyToString (key)]! = null}
First perform a string conversion on the incoming key, and then determine whether the key value is null or undefined.
2.set method
The set method is used to add key-value pairs to the dictionary:
Set (key, value) {if (key! = null & & value! = null) {let table_key = keyToString (key) this.table [table _ key] = new ValuePair (key, value) return true} return false} 3.remove method
The remove method is used to delete a key-value pair from the dictionary:
Remove (key) {if (this.hasKey (key)) {delete th.table [keyToString (key)] return true} return false} 4.get method
The get method is used to get the key value corresponding to the key name:
Get (key) {if (this.hasKey (key)) {let table_key = keyToString (key) return table [table _ key]. Value} return undefined} 5.keys, values, keyValues method
These three are relatively simple auxiliary functions, which are introduced together:
KeyValues () {return Object.values (this.table)} keys () {return this.keyValues (). Map (valuePair= > valuePair.key)} values () {return this.keyValues () .map (valuePair= > valuePair.value)}
First, the keyValues method returns all the key values of the dictionary as an array, and the result is an array of ValuePair instances. Then on the basis of this function, the corresponding key array and value array are obtained respectively.
6.forEach method
The forEach method has the same function as the forEach method of the array, which iterates over all the elements. Let's take a look at how all the values of the iterative dictionary are implemented:
ForEach (callFn) {let valuePairs = this.keyValues () for (let I = 0; I
< valuePairs.length; i++) { let result = callFn(valuePairs[i].key, valuePairs[i].value) if(result === false) break; }} 首先传一个回调函数作为参数,然后遍历字典的长度,并在循环里调用这个回调函数。这里我们的一个设计是,如果在回调函数内返回 false,则会中断循环。 7.clear, size, isEmpty 方法 这个三个方法也比较基础: size() { return Object.keys(this.table).length;}isEmpty() { return this.size() === 0}clear() { this.table = {}}三、使用字典 前面我们写了不少方法实现了一个字典类,现在来使用一下: var dict = new Dictionary();dict.set("name", "赛罗");dict.set("color", "红蓝");dict.set("skill", "头标"); 添加了三个键值对,我们看一下基本方法的返回结果: console.log(dict.keys()); // ['name', 'color', 'skill']console.log(dict.values()); // ['赛罗', '红蓝', '头标']console.log(dict.size()); // 3console.log(dict.hasKey("color")); // trueconsole.log(dict.get("color")); // 红蓝console.log(dict.hasKey("like")); // falseconsole.log(dict.get("like")); // undefined 看结果都没问题,再来一波遍历: dict.forEach((key, value) =>{console.log (key, value); if (key = "color") return false;}); / / print result: / / name Cerro / / color red and blue
It can be seen that there is no problem with the loop traversal, and when the function execution returns false, the traversal is terminated, so the third key-value pair is not printed and the result is up to standard.
Finally, take a look at the deletion:
/ delete key-value pairs console.log (dict.remove ("color")); / / trueconsole.log (dict.remove ("like")); / / falseconsole.log (dict.remove ("skill")); / / trueconsole.log (dict.keyValues ()); / / [ValuePair] console.log (dict.hasKey ("color")); falseconsole.log (dict.size ()); 1Chart / empty dictionary dict.clear (); console.log (dict.keyValues ()) / / [] console.log (dict.isEmpty ()); / / the above true is all the contents of the article "how to use the dictionary method of JavaScript data structures". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.