var s = new Set();
[2, 3, 5, 4, 5, 2, 2].map(x => s.add(x));
for (let i of s) {
console.log(i);
}
备注
// 例一
var set = new Set([1, 2, 3, 4, 4]);
[...set] // 用...(展开操作符)操作符将Set转换为Array
// [1, 2, 3, 4]
// 例二
var items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5
// 例三
function divs () {
return [...document.querySelectorAll('div')];
}
var set = new Set(divs());
set.size // 56
// 类似于
divs().forEach(div => set.add(div));
set.size // 56
// 去除数组的重复成员array
[...new Set(array)]
var items = new Set([1, 2, 3, 4, 5]);
var array = Array.from(items);
// 数组去重
function dedupe(array) {
return Array.from(new Set(array));
}
dedupe([1, 1, 2, 3]); // [1,2,3]
let set = new Set();
let a = NaN;
let b = NaN;
set.add(a);
set.add(b);
set // Set {NaN}
let set = new Set();
set.add({});
set.size // 1
set.add({});
set.size // 2
var obj = {};
class S extends Set {}
var set = new S();
set.add(123);
set.add(123);
console.log(set instanceof S && set.has(123));
Set.prototype.constructor: 构造函数,默认就是Set函数.
Set.prototype.size: 返回Set实例的成员总数.
操作方法(用于操作数据)
let set = new Set();
set.add('pl');
set.add('pl');
console.log(set.size);
console.log(set.has('pl'));
set.add('xg');
console.log(set.size);
set.delete('xg');
console.log(set.size);
set.add('xg');
console.log(set.size);
set.clear();
console.log(set.size);
遍历方法(用于遍历成员)
let set = new Set(['red', 'green', 'blue']);
console.log(set.values());
console.log(set.keys());
console.log(set.entries());
// 键值、键名、集合本身
function fun(value1, value2, set){
console.log("s[" + value1 + "] = " + value2);
console.log(set);
}
set.forEach(fun);
备注
Set.prototype[Symbol.iterator] === Set.prototype.values
let set = new Set(['red', 'green', 'blue']);
for (let x of set) {
console.log(x);
}
遍历的应用
let set = new Set(['red', 'green', 'blue']);
let arr = [...set];
console.log(arr);
let set = new Set([1, 2, 3]);
set = new Set([...set].map(x => x * 2));
console.log(set); // {2, 4, 6}
let set = new Set([1, 2, 3, 4, 5]);
set = new Set([...set].filter(x => (x % 2) == 0)); // {2, 4}
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]);
console.log(union); // Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
console.log(intersect); // Set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference); // [1]
通过变通方法实现遍历操作中改变原来的Set结构
let set = new Set([1, 2, 3]);
set = new Set([...set].map(val => val * 2));
console.log(set); // Set {2, 4, 6}
let set = new Set([1, 2, 3]);
set = new Set(Array.from(set, val => val * 2));
console.log(set); // Set {2, 4, 6}
var data = {};
var element = document.getElementsByTagName("div")[0];
data[element] = 'hello world';
console.log(data["[object HTMLDivElement]"]); //hello world
var map = new Map([['name', '张三'], ['title', 'Author']]);
console.log(map); //Map {"name" => "张三", "title" => "Author"
let map = new Map();
map.set(1, 'aaa').set(1, 'bbb');
console.log(map.get(1)); // "bbb"
console.log(new Map().get('asfddfsasadf'));
var map = new Map();
map.set(['a'], 555);
console.log(map.get(['a'])) // undefined
var map = new Map();
var k1 = ['a'];
var k2 = ['a'];
map
.set(k1, 111)
.set(k2, 222);
console.log(map.get(k1)); // 111
console.log(map.get(k2)); // 222
var obj = {name: 'pl'};
map.set(obj, 'lulu')
console.log(map.get(obj)); //lulu
let map = new Map();
map.set(NaN, 123);
console.log(map.get(NaN)); // 123
map.set(-0, 123);
console.log(map.get(+0)); // 123
var key = {};
class M extends Map {}
var map = new M();
map.set(key, 123);
console.log(map instanceof M && map.has(key) && map.get(key) === 123); // true
let map = new Map();
map.set('foo', true);
map.set('bar', false);
console.log(map.size); // 2
var m = new Map();
m.set("edition", 6); // 键是字符串
m.set(262, "standard"); // 键是数值
cosnole.log(m.set(undefined, "nah")); // 键是undefined
- set方法返回的是Map本身,因此可以采用链式写法。
let map1 = new Map()
.set(1, 'a')
.set(2, 'b')
.set(3, 'c');
console.log(map1);
var m = new Map();
var hello = function() {console.log("hello");}
m.set(hello, "Hello ES6!") // 键是函数
console.log(m.get(hello)); // Hello ES6!
console.log(m.get('name')); // undefined
var m = new Map();
m.set("edition", 6);
m.set(262, "standard");
m.set(undefined, "nah");
console.log(m.has("edition")); // true
console.log(m.has("years")); // false
console.log(m.has(262)); // true
console.log(m.has(undefined)); // true
var m = new Map();
m.set(undefined, "nah");
console.log(m.has(undefined)); // true
console.log(m.delete(undefined)); // true
console.log(m.has(undefined)); // false
console.log(m.delete(undefined)); // false
let map = new Map();
map.set('foo', true);
map.set('bar', false);
console.log(map.size); // 2
map.clear()
console.log(map.size); // 0
let map = new Map([
['F', 'no'],
['T', 'yes'],
]);
console.log(map.keys()); // MapIterator {"F", "T"}
for (let key of map.keys()) {
console.log(key);
}
console.log(map.values()); //MapIterator {"no", "yes"}
for (let value of map.values()) {
console.log(value);
}
// console.log(map.entries()); // MapIterator {["F", "no"], ["T", "yes"]}
for (let item of map.entries()) {
console.log(item[0], item[1]);
}
// 或者
for (let [key, value] of map.entries()) {
console.log(key, value);
}
// 等同于使用map.entries()
for (let [key, value] of map) {
console.log(key, value);
}
map.forEach(function(value, key, map){
console.log("Key: " + key + " Value:" + value);
})
Map.prototype[Symbol.iterator] === Map.prototype.entries
let 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']]
console.log([...map]); // [[1,'one'], [2, 'two'], [3, 'three']]
let map0 = new Map()
.set(1, 'a')
.set(2, 'b')
.set(3, 'c');
let map1 = new Map(
[...map0].filter(([k, v]) => k < 3)
);
console.log(map1); // Map {1 => "a", 2 => "b"}
let map2 = new Map(
[...map0].map(([k, v]) => [k * 2, '_' + v])
);
console.log(map2); // Map {2 => "_a", 4 => "_b", 6 => "_c"}
let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);
console.log([...myMap]); //[[true,7],[{foo: 3},{0: 'abc'}]]
console.log(new Map([[true, 7], [{foo: 3}, ['abc']]])); //Map {true => 7, Object {foo: 3} => Object {0: "abc"}}
function strMapToObj(strMap) {
let obj = Object.create(null);
for (let [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
let myMap = new Map().set('yes', true).set('no', false);
console.log(strMapToObj(myMap)) ; // Object {yes: true, no: false}
function objToStrMap(obj) {
let strMap = new Map();
for (let k of Object.keys(obj)) {
strMap.set(k, obj[k]);
}
return strMap;
}
console.log(objToStrMap({yes: true, no: false})); // Map {"yes" => true, "no" => false}
Map转为JSON
function strMapToObj(strMap) {
let obj = Object.create(null);
for (let [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
function strMapToJson(strMap) {
return JSON.stringify(strMapToObj(strMap));
}
let myMap = new Map().set('yes', true).set('no', false);
console.log(strMapToJson(myMap)); //{"yes":true,"no":false}
function mapToArrayJson(map) {
return JSON.stringify([...map]);
}
let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);
console.log(mapToArrayJson(myMap)); // [[true,7],[{"foo":3},["abc"]]]
JSON转为Map
function objToStrMap(obj) {
let strMap = new Map();
for (let k of Object.keys(obj)) {
strMap.set(k, obj[k]);
}
return strMap;
}
function jsonToStrMap(jsonStr) {
return objToStrMap(JSON.parse(jsonStr));
}
console.log(jsonToStrMap('{"yes":true,"no":false}')); // Map {"yes" => true, "no" => false}
function jsonToMap(jsonStr) {
return new Map(JSON.parse(jsonStr));
}
console.log(jsonToMap('[[true,7],[{"foo":3},["abc"]]]')); //Map {true => 7, Object {foo: 3} => ["abc"]}