Interview question: ES6 adds two new reference data types, Set and Map, to solve what problems? What is the difference between weakSet and weakMap and Set and Map?

foreword

Before answering this question, we must first understand the characteristics of Set and Map , and combine their characteristics to answer this question.

If you find any mistakes or ambiguities in the article, I hope you can point it out to avoid misleading more people! !


text

1. set

basic use

Set objects allow you to store unique values ​​of any type , whether primitive values ​​or object references. It is similar to an array, but the values ​​of the members are all unique and there are no duplicate values .

  • Both null and undefined can be stored in Set
  • NaNs are considered the same value (NaNs are considered the same, although NaN !== NaN).
  • Two objects are always unequal (addresses are different), even empty objects.

Set()A new Set object can be created using .

const s = new Set();
// add()方法向 Set 结构加入成员
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));

for (let i of s) {
    
    
  console.log(i);
}
// 输出:2 3 5 4

The Set function can accept an array (or other data structure with an iterable interface) as a parameter for initialization.

const set = new Set([1, 2, 3, 4, 4]);
console.log([...set]); // [1, 2, 3, 4]

const set=new Set('ababbc');
console.log(set); //Set(3) { 'a', 'b', 'c' }

So we can use it to achieve array deduplication or string deduplication

// 去除数组的重复成员
[...new Set([1,2,1,3,4])]  //[ 1, 2, 3, 4 ]

//去除字符串里面的重复字符。
[...new Set('ababbc')].join('') // "abc"

properties and methods

Set.prototype.size

Set.prototype.size: Returns the total number of members of the Set instance.

let set=new Set()
set.add({
    
    });
set.add({
    
    });
console.log(set.size);  //2

Set.prototype.add(value)

add()method is used to add a specified value to the end of a Set object. The return value is the Set object itself.

let set=new Set()
set.add(1).add(2).add(2).add(3);
console.log(set.size); //3

Set.prototype.delete(value)

delete()Method removes the specified element from a Set object.

var mySet = new Set();
mySet.add("foo");
console.log(mySet.delete("bar")); // 返回 false,不包含 "bar" 这个元素
console.log(mySet.delete("foo")); // 返回 true,删除成功

Set.prototype.has(value)

has()The method returns a boolean value to indicate whether the corresponding value value exists in the Set object.

var mySet = new Set();
mySet.add("foo");
console.log(mySet.has("foo")); // 返回 true
console.log(mySet.has("bar")); // 返回 false

Set.prototype.clear()

clear()The method is used to clear all elements in a Set object.

var mySet = new Set();
mySet.add(1);
mySet.add(2);
console.log(mySet.size); // 2
mySet.clear()
console.log(mySet.size); // 0

Set.prototype.entries()

entries()The method returns a new iterator object. Returns a new array iterator object of the form [value, value], where value is each element in the given collection, and the order of the elements of the iterator object is the order in which the elements in the collection object were inserted.

var mySet = new Set();
mySet.add("foobar");
mySet.add(1);
mySet.add("baz");
var setIter = mySet.entries();
console.log(setIter.next().value); // ["foobar", "foobar"]
console.log(setIter.next().value); // [1, 1]
console.log(setIter.next().value); // ["baz", "baz"]

Set.prototype.forEach()

forEachThe method executes the provided callback function in sequence according to the insertion order of the elements in the collection.

var set=new Set()
set.add('hello')
set.add('world')
set.forEach((currentValue, currentKey)=>{
    
    
    console.log(currentValue,currentKey);
})
//hello hello
//world world

Set.prototype.values()

values()The method returns a new Iterator object with the value of each element of the Set object in the order in which the elements were inserted.

var set=new Set()
set.add('hello')
set.add('world')
const iterator1 = set.values();
console.log(iterator1.next().value); //hello
console.log(iterator1.next().value); //world

spread operator (…)

The spread operator (…) uses a for…of loop internally, so it can also be used with Set structures.

let set = new Set(['red', 'green', 'blue']);
let arr = [...set]; // ['red', 'green', 'blue']

2.WeakSet

WeakSet objects allow you to store weakly held objects in a collection .

var Wset = new WeakSet([[1, 2], [3, 4]])
console.log(Wset); //WeakSet {[1, 2], [3, 4]}

WeakSet structure is similar to Set, and it is also a collection of unique values. However, it differs from Set in two ways.

  • Members of WeakSet can only be objects , not other types of values.
  • Objects in WeakSet are weak references . If there are no other references to objects in the WeakSet, those objects will be garbage collected. This also means that there is no list of current objects stored in the WeakSet. Because of this, WeakSet is not enumerable .

WeakSet is not traversable, has no size attribute, and no clear() method. There are three methods that are the same as set :

WeakSet.prototype.add(value):向 WeakSet 实例添加一个新成员。
WeakSet.prototype.delete(value):清除 WeakSet 实例的指定成员。
WeakSet.prototype.has(value):返回一个布尔值,表示某个值是否在

3.Map

Map objects hold key-value pairs and are able to remember the original insertion order of keys. Any value (object or primitive) can be used as a key or a value.

  • Map does not contain any keys by default. Only explicitly inserted keys are included . An Object has a prototype, and the key name on the prototype chain may conflict with the key name you set on the object.
  • The keys of a Map can be any value, including functions, objects, or any primitive type. An Object key must be a String or Symbol.
  • Map performs better in scenarios where key-value pairs are frequently added or deleted.

basic use

Map()Create a Map object using the constructor . Map can also accept an array as a parameter. The members of this array are arrays of key-value pairs. Any data structure with an Iterator interface where each member is an array of two elements can be used as an argument to the Map constructor

let myMap = new Map();

const map = new Map([
  ['name', '张三'],
  ['title', 'Author']
]);

Attributes

sizeis an accessible property that returns the number of members of a Map object.

const map = new Map();
map.set('foo', true);
map.set('bar', false);
console.log(map.size ); // 2

basic method

Map.prototype.set(key, value)

set()The method adds or updates a (new) key-value pair with a specified key and value to a Map object, which returns a Map object

let map = new Map()
  .set(1, 'a')
  .set(2, 'b')
  .set(3, 'c');
console.log(map.size); // 3

Map.prototype.get(key)

get()The method returns a specified element in a Map object, which returns the value associated with the specified key in a Map object, or undefined if the key is not found.

var myMap = new Map();
myMap.set("bar", "foo");

myMap.get("bar");  // 返回 "foo"
myMap.get("baz");  // 返回 undefined

Map.prototype.has(key)

has()Returns a bool value indicating whether the specified element exists in the map.

var myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.has("bar"));  // 返回 true
console.log( myMap.has("baz"));  // 返回 false

Map.prototype.delete(key)

delete()method is used to remove the specified element in the Map object. Removes the element and returns true if the element exists in the Map object; otherwise returns false if the element does not exist.

var myMap = new Map();
myMap.set("bar", "foo");

console.log(myMap.delete("bar")); // 返回 true。成功地移除元素
console.log(myMap.has("bar"));   // 返回 false。"bar" 元素将不再存在于 Map 实例中

Map.prototype.clear()

clear()The method removes all elements in the Map object.

let map = new Map();
map.set('foo', true);
map.set('bar', false);

map.size // 2
map.clear()
map.size // 0

Map.prototype.entries()

The entries() method returns a new Iterator object containing [key, value] pairs in the same iteration order as the Map object was inserted.

const map1 = new Map();

map1.set('0', 'foo');
map1.set(1, 'bar');

const iterator1 = map1.entries();

console.log(iterator1.next().value);
// expected output: ["0", "foo"]

console.log(iterator1.next().value);
// expected output: [1, "bar"]

other traversal

  • Map.prototype.keys(): Returns a traverser of key names.
  • Map.prototype.values(): Returns a traverser of key values.
  • Map.prototype.forEach(): Iterates over all members of the Map.
  • for…of…

A quicker way to convert a Map structure to an array structure is to use the spread operator (…).

const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

console.log([...map.keys()])// [1, 2, 3]);
console.log([...map.values()]); // ['one', 'two', 'three']
console.log([...map.entries()]); // [[1,'one'], [2, 'two'], [3, 'three']]

4. WeakMap

A WeakMap object is a collection of key/value pairs where the keys are weakly referenced . Its keys must be objects, and the values ​​can be arbitrary.

A native WeakMap holds a "weak reference" to each key object, which means that garbage collection can proceed correctly when no other references exist. Because of such weak references, the keys of WeakMap are not enumerable.

  • WeakMap(): Creates a new WeakMap object.
  • WeakMap.prototype.delete(key): Deletes the value associated with the key in the WeakMap.
  • WeakMap.prototype.get(key): Returns the value associated with the key in the WeakMap, or undefined if the key does not exist.
  • WeakMap.prototype.has(key): Returns a boolean that asserts whether a value is already associated with the key in the WeakMap object.
  • WeakMap.prototype.set(key, value): Set a value to the key in WeakMap. This method returns a WeakMap object.

question answer

1. Why are Set and Map added, and what problems are they solving?

The values ​​of the members of a set are all unique, with no duplicate elements , while an array is not.
The keys of a Map can be any value, including functions, objects, or any primitive type. But an Object key must be a String or Symbol. The Map structure provides a "value-value" correspondence and is a more complete implementation of the Hash structure.

2. weakSet and weakMap compared to Set and Map

Members of WeakSet must be objects and weak references . The keys
of WeakMap must be objects and weak references . can't enumerate

Guess you like

Origin blog.csdn.net/qq_45890970/article/details/123639035