扫码关注官方订阅号
用push只是把数据存入数据,怎么实现存在数组里的数据是键值对的形式?
认证0级讲师
arr.push({ value : value })
var array=[]; array.push('1'); array['test']='2'; console.log(array);
如果特别喜欢键值对,那么可以考虑:Map,使用方法如下:
var myMap = new Map(); //塞入键值对 myMap.set('cityName', 'Beijing'); myMap.set('cityPopulation', 2152); //遍历 myMap.forEach(function(value, key) { console.log(key + ' = ' + value); });
//cityName = Beijing//cityPopulation = 2152
当然你也可以直接使用字面量形式表达,如下:
var myMap = {}; //塞入键值对 myMap['cityName'] = 'Beijing'; myMap['cityPopulation'] = 2152; //遍历 for(var key in myMap){ console.log(key + ' = ' + myMap[key]); } //cityName = Beijing //cityPopulation = 2152
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
如果特别喜欢键值对,那么可以考虑:Map,使用方法如下:
//cityName = Beijing
//cityPopulation = 2152
当然你也可以直接使用字面量形式表达,如下: