在javascript中,对象本身就是一种Map结构。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var map = {}; map[ 'key1' ] = 1; map[ 'key2@' ] = 2; console.log(map[ 'key1' ]); //结果是1. console.log(map[ 'key2@' ]); //结果是2. //如果遍历map for ( var prop in map){ if (map.hasOwnProperty(prop)){ console.log( 'key is ' + prop + ' and value is' + map[prop]); } } |
动态的赋值key
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
var key1 = '动态key1' ; var key2 = '动态key2' ; var map = {}; map[key1] = 1; map[key2] = 2; console.log(map[key1]); //结果是1. console.log(map[key2]); //结果是2. //如果遍历map for ( var prop in map){ if (map.hasOwnProperty(prop)){ console.log( 'key is ' + prop + ' and value is' + map[prop]); } } |