# Map Map 对象保存键值对。任何值(对象或者基本类型)都可以作为一个键或一个值。 **注意:请勿使用下标访问或设置map的键值对,此用法虽然在uts转为kotlin时可用,但是并不跨端** ```ts const map = new Map() map['key1'] = 'value1' // 不跨端的用法 map.set('key1', 'value1') // 跨端用法 console.log(map['key1']) // 不跨端的用法 console.log(map.get('key1')) // 跨端用法 ``` ### Constructor() ### Constructor(entries?)_1 ## 实例属性 ### size ```ts const map1 = new Map(); map1.set('a', 'alpha'); map1.set('b', 'beta'); map1.set('g', 'gamma'); console.log(map1.size); // expected output: 3 ``` ## 实例方法 ### clear() ```ts const map1 = new Map(); map1.set('bar', 'baz'); map1.set(1, 'foo'); console.log(map1.size); // expected output: 2 map1.clear(); console.log(map1.size); // expected output: 0 ``` ### delete(key) ```ts const map1 = new Map(); map1.set('bar', 'foo'); console.log(map1.delete('bar')); // expected result: true // (true indicates successful removal) console.log(map1.has('bar')); // expected result: false ``` ### forEach(callbackfn, thisArg?) ```ts let mapObj = new Map() mapObj.put("name","zhangsan") mapObj.put("age",12) // 需要特别注意迭代方法的第一个参数是value.第二个是key. mapObj.forEach(function(value:any,key:string){ console.log(key) console.log(value) }) ``` ### get(key) ```ts const map1 = new Map(); map1.set('bar', 'foo'); console.log(map1.get('bar')); // expected output: "foo" ``` ### has(key) ```ts const map1 = new Map(); map1.set('bar', 'foo'); console.log(map1.has('bar')); // expected output: true console.log(map1.has('baz')); // expected output: false ``` ### set(key, value) ```ts const map1 = new Map(); map1.set('bar', 'foo'); console.log(map1.get('bar')); // expected output: "foo" console.log(map1.get('baz')); // expected output: null ``` 注意:由于Map的key是唯一的,给同一个key多次set值时,会用新值替换老值。 ```ts const map1: Map = new Map(); //定义一个map,key为string类型,value也是string类型 map1.set('key1', "abc"); map1.set('key1', "def"); console.log(map1.get('key1')) //返回 def ``` ## 常见操作 - 创建map ```ts let map = new Map() map.set("name","zhangsan") map.set("age",12) //Map(2) {"name":"zhangsan","age":12} console.log(map) ``` - 通过key访问map元素 ```ts let map = new Map() map.set("name","zhangsan") map.set("age",12) let nameVal = map['name'] //zhangsan console.log(nameVal) ``` - 遍历map ```ts let map = new Map() map.set("name","zhangsan") map.set("age",12) // 遍历函数 1 map.forEach(function(value:any | null){ console.log(value) }) // 遍历函数 2 map.forEach(function(value:any | null,key:string){ console.log(key) console.log(value) }) // 遍历函数 3 map.forEach(function(value:any | null,key:string,map: Map){ console.log(value) console.log(key) console.log(map) }) ```