export default class Dictionary {
private items = {};
public length: number = 0;
constructor(key?:any[],value?:any[]){
if(!key || !value){
return;
}
if(key.length != value.length){
console.log("%c The length of the key and value do not match.", "color:#FF0000");
return;
}
for(var i = 0; i < key.length; ++i){
if(this.has(key[i])){
//有相同的键
var last_value = this.get(key[i]);
console.log("%c The key already has a value( %c " + last_value +") and will be overwritten by the value( %c "+ value[i] +")", "color:#FF0000","color:#0000FF","color:#00FF00");
}
this.set(key[i],value[i]);
}
}
/**
* @param key 键
* @returns 是否包含
*/
public has(key: any): boolean {
return key in this.items;
}
/**
* @param key 键
* @param valye 值
*/
public set(key: any, value: any) {
this.items[key] = value;
this.length = this.get_length();
}
/**
* @param
* @returns 查找结果,如果未查询到返回undefined
*/
public get(key: any) {
return this.has(key) ? this.items[key] : undefined;
}
/**
*
* @param key
* @param item
* @param create 如果未查询到是否自动创建,ps:默认自动创建
*/
public push(key:any,item:any,create :boolean = true){
if(this.has(key)){
var items = this.get(key);
items.push(item);
this.set(key,items);
}else{
if(create){
var new_items = [item];
this.set(key,new_items);
console.log("%c key : " + key + " not found.will craete one", "color:#FF0000");
}else{
console.log("%c key : " + key + " not found.", "color:#FF0000");
}
}
}
/**
* 获取当前字典中所有的键数组
* @returns 所有键的数组
*/
public all_key(): string[] {
var values: string[] = [];
for (var key in this.items) {
values.push(key)
}
return values;
}
/**
* @param key 键
* @returns 是否移除成功
*/
public remove(key: any): boolean {
if (this.has(key)) {
delete this.items[key];
this.length = this.get_length();
return true;
} else {
console.log("%c key : " + key + " not found.", "color:#FF0000");
}
return false;
}
/**
* 移除指定单元
* @param key
* @param item
* @returns 是否移除成功
*/
public remove_item(key: any, item: any) {
if (this.has(key)) {
var items = this.get(key);
for (var i = 0; i < items.length; ++i) {
if (items[i] == item) {
items.splice(i, 1);
break;
}
}
this.set(key, items);
this.length = this.get_length();
return true;
} else {
console.log("%c key : " + key + " not found.", "color:#FF0000");
}
return false;
}
/**
* 清理字典
*/
public clear() {
this.items = {};
this.length = 0;
}
/**
* 复制地点
* @returns 新的字典
*/
public copy(): Dictionary {
var dic = new Dictionary();
var all = this.all_key();
for (var i = 0; i < all.length; ++i) {
dic.set(all[i], this.get(all[i]));
}
dic.length = this.length;
return dic;
}
/**
* 字典的长度
* @returns 字典的长度
*/
private get_length(): number {
return Object.keys(this.items).length;
}
}
Cocos Creator Dictionary
于 2023-10-12 16:45:03 首次发布