Details of the ES6 JavaScript syntax structure of the new Map Data

Data are specific things, the type of a scope, structure (set) different combinations of data
. ES6 provide a "value - the value" data structure, the key name not only can be a string, it can also be a target. It is a better structure Hash

Map of creation

Map as a function of the parameter contents received can be an array, and a two-dimensional array, and a second two-dimensional array of data only, if there are multiple, not resolved.

var m1 = new Map( [ ["hel","world"] , [2,3] ] );
//只能解析数组中的前两个
var m2 = new Map( [  ["a","b","c"] , [2,34] ] );
const m3 = new Map([['name', 'Aissen'],['age', 12]])
console.log(m1);
console.log(m2);
console.log(m3);

Map method

	var m = new Map([["hello","world"],["a","b"],[2,3]]);
    //不能正常使用对象的方法,例如↓↓↓↓
	console.log(m.hello);              //undefined

	//下边是Map的的方法,例如↓↓↓↓
	//1.查看Map数据的长度的方法
    console.log(m.size);			

	//2.遍历Map数据的方法
    m.forEach(function(val,idx,self){
         console.log(val,idx,self);
    })

	//3.判断是否有键存在的Map成员,参数要写键,而不是值。返回值为布尔值
     console.log(m.has("a"));
     console.log(m.has("hello"));
     console.log(m.has("world"));		//false

	//4.删除某个值,返回值为布尔值
    m.delete("hello");
	console.log(m);		

	//5.清除所有成员,没有返回值
    m.clear();
	console.log(m);				//{}
//6.添加设置键值对的方法set()
var map4 = new Map();
map4.set('k1', 6)        // 键是字符串
map4.set(222, '哈哈哈')     // 键是数值
map4.set(undefined, 'gagaga')    // 键是 undefined

var fun = function() {console.log('hello');}
map4.set(fun, 'fun') // 键是 function
//7.获取键对应的值的方法get()
var a = map4.get("k1"));
console.log(a);

Map structure into an array

const map10 = new Map();
map10.set('k1', 1);
map10.set('k2', 2);
map10.set('k3', 3);
console.log([...map10]);	//解构

Map structure into an array

const map11 = new Map([
  ['name', 'Aissen'],
  ['age', 12]
])
console.log(map11)

Map structure into Set construction

function mapToSet(map) {
  let set = new Set()
  for (let [k,v] of map) {
    set.add([k, v])
  }
  return set;
}

const map14 = new Map()
  .set('k1', 1)
  .set({pa:1}, 2);
console.log(mapToSet(map14))

Set structure into the structure Map

const set = new Set([
  ['foo', 1],
  ['bar', 2]
]);
const map13 = new Map(set)
console.log(map13)
Published 18 original articles · won praise 35 · views 2157

Guess you like

Origin blog.csdn.net/wxd_97/article/details/104965410