<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
//js模拟java Map数组——主要利用对象的键值对特性解决
function Map() {
this.mapArr = {};
this.arrLength=0;
//判断是否包含相同的key键 如果包含返回false 不保存值
this.contains = function(_key) {
return (_key in this.mapArr); //利用in关键字进行判断 mapArr对象是否拥有)_key属性
}
//根据key键和value值添加入map
this.put = function(_key,_value) {
if(!this.contains(_key)) {
this.mapArr[_key] = _value;
this.arrLength++;
return "添加值成功";
}else{
return "key值重复请重新输入";
}
}
//根据key键获得value值
this.getValue = function (_key) {
if(this.contains(_key)) {
return this.mapArr[_key];
}else{
return "map值不存在";
}
}
//通过返回变量长度得到对象的长度
this.getSize = function() {
return this.arrLength;
}
//通过key值删除map中的value值
this.remove = function(_key) {
if(this.contains(_key)) {
//通过delete关键字删除对象属性
delete this.mapArr[_key];
//删除key的时候通知把变量对象长度减1
this.arrLength--;
return "删除成功";
}else{
return "key值不存在";
}
}
//通过回调函数打印值 遍历map
this.each = function(callback) {
if(typeof callback === "function") {
for(var i in this.mapArr) {
callback(i,this.mapArr[i]);
}
}else{
return "传参错误,应该传对象类型";
}
}
//清空map
this.clear = function() {
//重新赋值空对象和重新设置长度 达到模拟清空的目的
this.mapArr={};
this.arrLength = 0;
return "map清空成功"
}
}
var map = new Map();
console.log("根据key添加的值:"+map.put(12,120));
console.log("根据key添加的值:"+map.put(1,110));
console.log("根据key添加的值:"+map.put(1,110));
console.log("根据key添加的值:"+map.put(12,110));
console.log("根据key添加的值:"+map.put(3,110));
console.log(map.clear());
console.log("根据key添加的值:"+map.put(5,110));
console.log("根据key添加的值:"+map.put(4,110));
console.log("根据key得到的值为:"+map.getValue(1));
console.log("根据key得到的值为:"+map.getValue(3));
console.log("得到的map大小为:"+map.getSize());
console.log("根据key删除值:"+map.remove(1));
console.log("得到的map大小为:"+map.getSize());
console.log("根据key得到的值为:"+map.getValue(1));
map.each(function(_key,_value) {
console.log(_key,_value);
});
</script>
</head>
<body>
</body>
</html>