JavaScript Map 实现
2024-08-27 10:11:09
//定义map
function Map() {
this.container = {};
}
//将key-value放入map中
Map.prototype.put = function(key, value) {
try {
if (key != null && key != "")
this.container[key] = value;
} catch (e) {
return e;
}
}; //根据key从map中取出对应的value
Map.prototype.get = function(key) {
try {
return this.container[key];
} catch (e) {
return e;
}
}; //判断map中是否包含指定的key
Map.prototype.containsKey = function(key) {
try {
for ( var p in this.container) {
if (p == key)
return true;
}
return false; } catch (e) {
return e;
} } //判断map中是否包含指定的value
Map.prototype.containsValue = function(value) {
try {
for ( var p in this.container) {
if (this.container[p] === value)
return true;
}
return false; } catch (e) {
return e;
}
}; //删除map中指定的key
Map.prototype.remove = function(key) {
try {
delete this.container[key];
} catch (e) {
return e;
}
}; //清空map
Map.prototype.clear = function() {
try {
delete this.container;
this.container = {}; } catch (e) {
return e;
}
}; //判断map是否为空
Map.prototype.isEmpty = function() { if (this.keySet().length == 0)
return true;
else
return false;
}; //获取map的大小
Map.prototype.size = function() { return this.keySet().length;
} //返回map中的key值数组
Map.prototype.keySet = function() {
var keys = new Array();
for ( var p in this.container) {
keys.push(p);
} return keys;
} //返回map中的values值数组
Map.prototype.values = function() {
var valuesArray = new Array();
var keys = this.keySet();
for (var i = 0; i < keys.length; i++) {
valuesArray.push(this.container[keys[i]]);
}
return valuesArray;
} //返回 map 中的 entrySet 对象
Map.prototype.entrySet = function() {
var array = new Array();
var keys = this.keySet();
for (var i = 0; i < keys.length; i++) {
array.push(keys[i],this.container[keys[i]]);
}
return array;
} //返回 map 中的 value值的和(当值是 Nunmber 类型时有效)
Map.prototype.sumValues = function() {
var values = this.values();
var result = 0;
for (var i = 0; i < values.length; i++) {
result += Number(values[i]);
}
return result;
} ///计算两个整数的百分比值
function toPercent(num, total){
num = parseFloat(num);
total = parseFloat(total);
if (isNaN(num) || isNaN(total)) {
return "0";
}
return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00 + "%");
// return (Math.round(this * 10000)/100).toFixed(2) + '%';
}
最新文章
- Anynote 基于ExtJS多用户个人信息管理系统
- Swagger .Net配置
- 使用srvany.exe将任何程序作为Windows服务运行
- Qt 调试时的错误——Debug Assertion Failed!
- sql联合查询去除重复计算总和
- I.MX6 build.prop
- PowerDesigner实用技巧小结(4)
- javascript技巧合集
- dede 留言板访问的目录
- js静态方法和实例方法
- 动态规划 最长公共子序列 LCS,最长单独递增子序列,最长公共子串
- Error: 17053 LogWriter: Operating system error 21(The device is not ready.)
- [DEEP LEARNING An MIT Press book in preparation]Deep Learning for AI
- SQL Server 文件路径
- PAT1011
- 【Swift 3.0】iOS 国际化切换语言
- 网络流Dinic(本篇介绍最大流)
- Linux基本指令
- Oracle管理表空间和数据文件详解
- springboot+dubbo+zookeeper微服务实践demo