`
luhantu
  • 浏览: 199912 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Dictionary 和 Object 的区别

    博客分类:
  • AS3
 
阅读更多

1. Dictionary 与 Object的区别在帮助文档中说的很清楚了:

 

Dictionary 类用于创建属性的动态集合,该集合使用全等运算符 (===) 进行键比较。将对象用作键时,会使用对象的标识来查找对象,而不是使用在对象上调用 toString() 所返回的值。Dictionary 集合中的原始(内置)对象(例如 Number)的行为方式与它们作为常规对象的属性时的行为方式相同。

 

并给出了例子:

 

 

var dict:Dictionary = new Dictionary();
var obj:Object = new Object();
var key:Object = new Object();
key.toString = function() { return "key" }
				
dict[key] = "Letters";
obj["key"] = "Letters";
				
dict[key] == "Letters"; // true
obj["key"] == "Letters"; // true 
obj[key] == "Letters"; // true because key == "key" is true because key.toString == "key"
dict["key"] == "Letters"; // false because "key" === key is false
delete dict[key]; //removes the key

 

 

2. 在这里,你还要理解 == 和 === 有何区别

 

在帮助文档中也做了很好的说明:

 

测试两个表达式是否相等,但不执行自动数据转换。如果两个表达式(包括它们的数据类型)相等,则结果为 true


 

全等运算符 (===) 与等于运算符 (==) 在以下三个方面相同:

  • 数字和布尔值按值进行比较,如果它们具有相同的值,则视为相等。
  • 如果字符串表达式具有相同的字符数,而且这些字符都相同,则这些字符串表达式相等。
  • 表示对象、数组和函数的变量按引用进行比较。如果两个这样的变量引用同一个对象、数组或函数,则它们相等。而两个单独的数组即使具有相同数量的元素,也永远不会被视为相等。

全等运算符 (===) 与等于运算符 (==) 仅在下列两个方面不同:

  • 全等运算符仅针对数字类型(Number、int 和 uint)执行自动数据转换,而等于运算符 () 针对所有的原始数据类型执行自动数据转换。
  • 当比较 nullundefined 时,全等运算符将返回 false
并给出了例子:

//下例说明当值和数据类型都匹配时,全等运算符 (===) 与等于运算符 (==) 相同: 
var string1:String = "5"; 
var string2:String = "5"; 
trace(string1 == string2);  // true 
trace(string1 === string2); // true
//下例说明全等运算符不将 String 类型的数据转换为 Number 类型的数据,但是等于运算符 (==) 却进行这样的转换: 
// The equality (==) operator converts 5 to "5", but the strict equality operator does not
var string1:String = "5"; 
var num:Number = 5; 
trace(string1 == num);  // true 
trace(string1 === num); // false 
//下例说明全等运算符不将布尔值转换为数字,但是等于运算符却进行这样的转换: 
var num:Number = 1;
var bool:Boolean = true;
trace(num == bool);  // true 
trace(num === bool); // false下例说明全等运算符确实转换 int 和 uint 数据类型: 
var num1:Number = 1;
var num2:int = 1;
var num3:uint = 1;
trace(num1 === num2); // true
trace(num1 === num3); // true下例说明全等运算符将 null 和 undefined 视为不相等,但是等于运算符却将它们视为相等: 
trace(null == undefined);  // true 
trace(null === undefined); // false 
 
3. 还要注意的是 hasOwnProperty() 方法
指示对象是否已经定义了指定的属性。如果目标对象具有与 name 参数指定的字符串匹配的属性,则此方法返回 true;否则返回 false
(在这里,你出入进去的是string 类型的值,即使你传入的是一个对象,它也会调用对象的toString()方法转化为string 然后进行比较.)
所以,如果你的dictionary的key值是对象,你怎么查找是否拥有此key值呢?
public function containsKey(key:*):Boolean
{
	for(var k:* in dict)
	{
		if(k === key)
		{
			return true;
		}
	}
	return dict.hasOwnProperty(key);
}
 
4.As3 中没有Map 类,不过可以自己模拟一个。
package
{
	import flash.utils.Dictionary;

	public class DictCache implements ICache
	{
		/**
		 *
		 * Defines the underlying object which contains the key / value
		 * mappings of an <code>ICache</code> implementation.
		 *
		 * @see http://livedocs.adobe.com/flex/3/langref/flash/utils/Dictionary.html
		 *
		 */
		protected var dict:Dictionary;

		/**
		 *
		 * Creates a new DictCache instance. By default, weak key
		 * references are used in order to ensure that objects are
		 * eligible for Garbage Collection immediatly after they
		 * are no longer being referenced, if the only reference to
		 * an object is in the specified Dictionary object, the key is
		 * eligible for garbage collection and is removed from the
		 * table when the object is collected 
		 * 
		 *
		 * @example
		 *
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache( false );
		 *
		 * </listing>
		 *
		 * @param specifies if weak key references should be used
		 *
		 */
		public function DictCache(weakReferences:Boolean=true)
		{
			dict = new Dictionary(weakReferences);
		}

		/**
		 *
		 * Adds a key and value to the DictCache instance
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "user", userVO );
		 *
		 * </listing>
		 *
		 * @param the key to add to the cache
		 * @param the value of the specified key
		 *
		 */
		public function put(key:*, value:*):void
		{
			dict[key] = value;
		}

		/**
		 *
		 * Places all name / value pairs into the current
		 * <code>IMap</code> instance.
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var table:Object = {a: "foo", b: "bar"};
		 * var cache:ICache = new DictCache();
		 * cache.putAll( table );
		 *
		 * trace( cache.getValues() );
		 * // foo, bar
		 *
		 * </listing>
		 *
		 * @param an <code>Object</code> of name / value pairs
		 *
		 */
		public function putAll(table:Dictionary):void
		{
			for (var prop:String in table)
			{
				put(prop, table[prop]);
			}
		}

		/**
		 *
		 * Removes a key and value from the DictCache instance
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.remove( "admin" );
		 *
		 * </listing>
		 *
		 * @param the key to remove from the cache
		 *
		 */
		public function remove(key:*):void
		{
			delete dict[key];
		}

		/**
		 *
		 * Determines if a key exists in the DictCache instance
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 *
		 * trace( cache.containsKey( "admin" ) ); //true
		 *
		 * </listing>
		 *
		 * @param  the key in which to determine existance in the cache
		 * @return true if the key exisits, false if not
		 *
		 */
		public function containsKey(key:*):Boolean
		{
			for(var k:* in dict)
			{
				if(k === key)
				{
					return true;
				}
			}
			return dict.hasOwnProperty(key);
		}

		/**
		 *
		 * Determines if a value exists in the DictCache instance
		 *
		 * <p>
		 * If multiple keys exists in the map with the same value,
		 * the first key located which is mapped to the specified
		 * key will be returned.
		 * </p>
		 *
		 * @example
		 *
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 *
		 * trace( cache.containsValue( adminVO ) ); //true
		 *
		 * </listing>
		 *
		 * @param  the value in which to determine existance in the cache
		 * @return true if the value exisits, false if not
		 *
		 */
		public function containsValue(value:*):Boolean
		{
			var result:Boolean=false;

			for (var key:* in dict)
			{
				if (dict[key] == value)
				{
					result=true;
					break;
				}
			}
			return result;
		}

		/**
		 *
		 * Returns the value of the specified key from the DictCache
		 * instance.
		 *
		 * <p>
		 * If multiple keys exists in the map with the same value,
		 * the first key located which is mapped to the specified
		 * value will be returned.
		 * </p>
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 *
		 * trace( cache.getKey( adminVO ) ); //admin
		 *
		 * </listing>
		 *
		 * @param  the key in which to retrieve the value of
		 * @return the value of the specified key
		 *
		 */
		public function getKey(value:*):*
		{
			var id:String=null;

			for (var key:*in dict)
			{
				if (dict[key] == value)
				{
					id=key;
					break;
				}
			}
			return id;
		}

		/**
		 *
		 * Returns each key added to the HashMap instance
		 *
		 * @example
		 *
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 *
		 * trace( cache.getKeys() ); //admin, editor
		 *
		 * </listing>
		 *
		 * @return Array of key identifiers
		 *
		 */
		public function getKeys():Array
		{
			var keys:Array=[];

			for (var key:* in dict)
			{
				keys.push(key);
			}
			return keys;
		}

		/**
		 *
		 * Retrieves the value of the specified key from the DictCache instance
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 *
		 * trace( cache.getValue( "editor" ) ); //[object, editorVO]
		 *
		 * </listing>
		 *
		 * @param  the key in which to retrieve the value of
		 * @return the value of the specified key, otherwise returns undefined
		 *
		 */
		public function getValue(key:*):*
		{
			return dict[key];
		}

		/**
		 *
		 * Retrieves each value assigned to each key in the DictCache instance
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 *
		 * trace( cache.getValues() ); //[object, adminVO],[object, editorVO]
		 *
		 * </listing>
		 *
		 * @return Array of values assigned for all keys in the cache
		 *
		 */
		public function getValues():Array
		{
			var values:Array=[];

			for (var key:* in dict)
			{
				values.push(dict[key]);
			}
			return values;
		}

		/**
		 *
		 * Determines the size of the HashMap instance
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 *
		 * trace( cache.size() ); //2
		 *
		 * </listing>
		 *
		 * @return the current size of the cache instance
		 *
		 */
		public function size():int
		{
			var length:int=0;

			for (var key:*in dict)
			{
				length++;
			}
			return length;
		}

		/**
		 *
		 * Determines if the current DictCache instance is empty
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var map:IMap = new HashMap();
		 * trace( map.isEmpty() ); //true
		 *
		 * map.put( "admin", adminVO );
		 * trace( map.isEmpty() ); //false
		 *
		 * </listing>
		 *
		 * @return true if the current map is empty, false if not
		 *
		 */
		public function isEmpty():Boolean
		{
			return size() <= 0;
		}

		/**
		 *
		 * Resets all key value assignments in the DictCache instance to null
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 * cache.reset();
		 *
		 * trace( cache.getValues() ); //null, null
		 *
		 * </listing>
		 *
		 */
		public function reset():void
		{
			for (var key:* in dict)
			{
				dict[key]=undefined;
			}
		}

		/**
		 *
		 * Resets all key / values defined in the DictCache instance to null
		 * with the exception of the specified key
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 *
		 * trace( cache.getValues() ); //[object, adminVO],[object, editorVO]
		 *
		 * cache.resetAllExcept( "editor", editorVO );
		 * trace( cache.getValues() ); //null,[object, editorVO]
		 *
		 * </listing>
		 *
		 * @param the key which is not to be cleared from the cache
		 *
		 */
		public function resetAllExcept(keyId:*):void
		{
			for (var key:* in dict)
			{
				if (key != keyId)
				{
					dict[key]=undefined;
				}
			}
		}

		/**
		 *
		 * Resets all key / values in the DictCache instance to null
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 * trace( cache.size() ); //2
		 *
		 * cache.clear();
		 * trace( cache.size() ); //0
		 *
		 * </listing>
		 *
		 */
		public function clear():void
		{
			for (var key:* in dict)
			{
				remove(key);
			}
		}

		/**
		 *
		 * Clears all key / values defined in the DictCache instance
		 * with the exception of the specified key
		 *
		 * @example
		 * <listing version="3.0">
		 *
		 * import com.lombardrisk.utils.DictCache;
		 * import com.lombardrisk.utils.ICache;
		 *
		 * var cache:ICache = new DictCache();
		 * cache.put( "admin", adminVO );
		 * cache.put( "editor", editorVO );
		 * trace( cache.size() ); //2
		 *
		 * cache.clearAllExcept( "editor", editorVO );
		 * trace( cache.getValues() ); //[object, editorVO]
		 * trace( cache.size() ); //1
		 *
		 * </listing>
		 *
		 * @param the key which is not to be cleared from the cache
		 *
		 */
		public function clearAllExcept(keyId:*):void
		{
			for (var key:* in dict)
			{
				if (key != keyId)
				{
					remove(key);
				}
			}
		}
	}
}
 ICache 类:

package
{
	import flash.utils.Dictionary;
	
	/**
     * 
     * Defines the contract for lightweight Cache implementations 
     * which are to expose an API into a managed collection of key 
     * value pairs
     * 
     */
	public interface ICache
	{
		 /**
         * 
         * Adds a key / value pair to the current cache
         * 
         * @param the key to add to the cache
         * @param the value of the specified key
         * 
         */
        function put(key:*, value:*) : void;
        
        /**
         *
         * Places all name / value pairs into the current
         * <code>ICache</code> instance.
         *  
         * @param an <code>Object</code> of name / value pairs
         * 
         */        
        function putAll(table:Dictionary) : void;        
         
        /**
         * 
         * Removes a key / value from the ICache instance
         *  
         * @param  key to remove from the cache
         * 
         */
        function remove(key:*) : void;

        /**
         * 
         * Determines if a key exists in the HashMap instance
         * 
         * @param  the key in which to determine existance in the map
         * @return true if the key exisits, false if not
         * 
         */
        function containsKey(key:*) : Boolean;

        /**
         * 
         * Determines if a value exists in the ICache instance
         * 
         * @param  the value in which to determine existance in the cache
         * @return true if the value exisits, false if not
         * 
         */
        function containsValue(value:*) : Boolean;

        /**
         * 
         * Returns a key value from the ICache instance
         * 
         * @param  the key in which to retrieve the value of
         * @return the value of the specified key
         * 
         */
        function getKey(value:*) : *;

        /**
         * 
         * Returns a key value from the ICache instance
         * 
         * @param  the key in which to retrieve the value of
         * @return the value of the specified key
         * 
         */
        function getValue(key:*) : *;

        /**
         * 
         * Returns each key added to the ICache instance
         * 
         * @return String Array of key identifiers
         * 
         */
        function getKeys() : Array;

        /**
         * 
         * Returns each value assigned to each key in the ICache instance
         * 
         * @return Array of values assigned for all keys in the cache
         * 
         */
        function getValues() : Array;
        
        /**
         * 
         * Retrieves the size of the ICache instance
         * 
         * @return the current size of the cache instance
         * 
         */
        function size() : int;

        /**
         * 
         * Determines if the HashMap instance is empty
         * 
         * @return true if the current map is empty, false if not
         * 
         */
        function isEmpty() : Boolean;
        
        /**
         * 
         * Resets all key value assignments in the ICache instance to null
         * 
         */
        function reset() : void;    
        
        /**
         * 
         * Resets all key / values defined in the ICache instance to null
         * 
         */
        function resetAllExcept(key:*) : void;    
                
        /**
         * 
         * Clears all key / values defined in the ICache instance
         * 
         */
        function clear() : void;

        /**
         * 
         * Clears all key / values defined in the ICache instance
         * with the exception of the specified key
         * 
         */
        function clearAllExcept(key:*) : void;
       
	}
}
 



 

分享到:
评论

相关推荐

    unity3d-ordered-dictionary:用于将有序字典添加到自定义`ScriptableObject`和`MonoBehaviour`类的库,只要键和值类型可序列化,可通过Unity对其进行序列化

    用于在自定义ScriptableObject和MonoBehaviour类中添加有序词典的库,只要键和值类型是可序列化的,就可以由Unity进行序列化。 $ yarn add rotorz/unity3d-ordered-dictionary 该软件包与工具兼容。 有关将程序​...

    iOS对象转字典 object2Dictionary

    iOS对象转字典 object2Dictionary 从项目中提取出来的,对象转为字典,对象转为json;

    Object2Dictionary:对象转字典,对象转json

    Object2Dictionary 对象转字典,对象转json -------------- 自定义对象 e.g. -------------- Header * header=[[Header alloc] init]; header.code=@"200"; header.message=@"成功"; Body * body=[[Body alloc...

    M13OrderedDictionary, 带有有序对象和键的NSDictionary.zip

    M13OrderedDictionary, 带有有序对象和键的NSDictionary M13OrderedDictionaryM13OrderedDictionary是NSArray和NSDictionary之间的交叉。 它包含一个有序的对象和键列表。 所有这些都可以通过索引或者键访问。 这里...

    Tool for Flatten A Folder

    命令行工具。拷贝多个目录下的指定文件到目标目录

    删除Javascript Object中间的key

    介绍了删除Javascript Object中间的key的方法,然后主要详谈了delete的用法,非常的详尽,给小伙伴们参考下

    字典语法基础

    '向 Dictionary 对象中添加一个关键字项目对。 'object.Add (key, item) 'Object '必选项。总是一个 Dictionary 对象的名称。 'Key '必选项。与被添加的 item 相关联的 key。 'Item '必选项。与被添加的 key 相...

    对python中Json与object转化的方法详解

    一个python object无法直接与json转化,只能先将对象转化成dictionary,再转化成json;对json,也只能先转换成dictionary,再转化成object,通过实践,源码如下: import json class user: def __init__(self, ...

    dictionary:添加一个简单的基于值的字典

    foo+bar 不会返回value(index)在索引处获取值index(value)获取值的索引如果值存在于字典中,则存在(值)返回真clone克隆列表并返回单词列表toArray返回字典中的单词列表toObject返回单词查找对象用法简而言之: ...

    iOS中setValue和setObject的区别详解

    网上关于setValue和setObject的区别的文章很多,说的并不准确,首先我们得知道: setObject:ForKey: 是NSMutableDictionary特有的;setValue:ForKey:是KVC的主要方法 话不多说,上代码: - (void)viewDidLoad { [super ...

    HashTable、HashSet和Dictionary的区别点总结

    今天又去面试了,结果依然很悲催,平时太过于关注表面上的东西,有些实质却不太清楚,遇到HashTable和Dictionary相关的知识,记录下来,希望对后来人有所帮助,以及对自己以后复习可以参考。 1.HashTable 哈希表...

    python(1).doc

    什么是 name space : name space 是 name 和 object 之间的映射关系。 每一个 name 唯一的和一个 object 绑定。 一个 object 可以有多个 name 。 如果没有 name 和 object 绑定,那么 object...

    SAP通用接口代码NCo3.0

    NCo3.0调用RFC,通用接口, 支持泛型和动态类型。 Sap通用接口  一、 接口说明 1. 入参Dictionary, string&gt;,出参泛型 1.1 接口ExecuteString public T ExecuteString(string FunName, Dictionary, string&gt;...

    Redis API文档 全称:Remote Dictionary Server 远程字典服务

    Redis(全称:Remote Dictionary Server 远程字典服务)是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由...

    JS中的算法与数据结构之字典(Dictionary)实例详解

    本文实例讲述了JS中的算法与数据结构之字典(Dictionary)...其实,JavaScript 中的 Object 类就是以字典的形式设计的,下面我们将会借助 Object 类的特性,自主实现一个 Dictionary 类,让这种字典类型的对象使用起来更

    Spring.NET学习笔记-实现一个简易的IoC框架

    通过这一点就可以告诉我们制作IoC容器需要写一个获取XML文件内容的方法和申明一个Dictionary, object&gt;来存放IoC容器中的对象,还需要写一个能从Dictionary, object&gt;中获取对象的方法。 全程手把手都你学习Srint.Net...

    LitJson工具源码导入能用,本人亲自修改版

    能将类,List,Dictionary类型转换成json同时也能反转换为实体 如以下类的转换案例,希望能帮助大家。 class A{ public int b = 1; public string c = "abcd...A a1 = JsonMapper.ToObject(json); 如有疑问请下方咨询

    CANopen high-level protocol for CAN-bus

    3.1 CANOPEN OBJECT DICTIONARY .... 3 3.2 CANOPEN COMMUNICATION......5 3.3 CANOPEN PREDEFINED CONNECTION SET...7 3.4 CANOPEN IDENTIFIER DISTRIBUTION ...8 3.5 CANOPEN BOOT-UP PROCESS .....9 3.6 ...

    使用 ConfigurationSection 创建自定义配置节

    public object Create(object parent, object configContext, XmlNode section) { List&lt;string&gt; addressList = new List(); string address; foreach (XmlNode childNode in section.ChildNodes) { if ...

    plist文件是标准的xml文件

    写入plist文件:(Dictionary/Array) NSMutableDictionary* dict = [ [ NSMutableDictionary alloc ] initWithContentsOfFile:@"/Sample.plist" ]; [ dict setObject:@"Yes" forKey:@"RestartSpringBoard" ]; [ dict ...

Global site tag (gtag.js) - Google Analytics