`
luhantu
  • 浏览: 204536 次
  • 性别: 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;
       
	}
}
 



 

分享到:
评论

相关推荐

    iOS对象转字典 object2Dictionary

    总结来说,"iOS对象转字典 object2Dictionary"这个主题涵盖了如何在Objective-C和Swift中将对象转换为字典,再将字典转换为JSON的过程。这些技术在移动应用的数据管理、网络请求和本地存储等方面都有广泛的应用。...

    如何获取object中的属性值

    Dictionary, object&gt; json = (Dictionary, object&gt;)serializer.Deserialize(jsonResult, typeof(Dictionary, object&gt;)); ``` 4. **获取嵌套属性值**: ```csharp object aa = json["xml"]; Dictionary, object...

    C#数组中List, Dictionary的相互转换问题

    将数组转换为Dictionary 将Dictionary 转换为数组 将List转换为Dictionary 将Dictionary转换为List 首先这里定义了一个“Student”的类,它有三个自动实现属性。 class Student { public int Id { get; set; ...

    C#中Json 解析类库,使用dictionary 解析未知字段的对象

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,因其简洁和易于阅读而被广泛应用。在C#中,我们经常使用各种类库来解析和序列化JSON,以进行数据的转换和操作。本篇文章将详细讲解如何在C#中使用...

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

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

    用Dictionary写的对象池

    Dictionary, Stack&lt;MyObject&gt;&gt; objectPool = new Dictionary, Stack&lt;MyObject&gt;&gt;(); ``` 2. 获取对象:当需要对象时,检查对象池中是否存在可重用的对象。如果存在,就从堆栈中弹出一个;如果不存在,根据需求新建一...

    Oracle Dictionary常用方法封装

    为了方便开发和管理,通常会将对Dictionary的常用操作封装成一个PackageBody,这就是"Oracle Dictionary常用方法封装"的主题。 在这个主题中,开发者创建了一个名为"ZL_Dictionary_Service"的包体(PackageBody),...

    Dictionary, SortedDictionary, SortedList 横向评测

    Dictionary 适合大规模数据的存储和检索,SortedDictionary 和 SortedList 适合需要排序的数据存储和检索。如果需要频繁地插入和移除元素,可以选择 SortedDictionary;如果需要频繁地检索元素,可以选择 Dictionary...

    ABAP SAP Dictionary

    ABAP SAP Dictionary是SAP系统中的一个重要组成部分,它是一个数据定义工具,用于创建、管理和维护SAP系统中的数据结构和业务对象。SAP Dictionary提供了一种标准化的方式来定义和描述数据库表、域、数据类型、搜索...

    HashTable、HashSet和Dictionary的区别点总结

    HashTable、HashSet和Dictionary的区别点总结 在C#中,HashTable、HashSet和Dictionary都是常用的集合类,但是它们之间有着很大的区别。本文将从 HashTable、HashSet和Dictionary的定义、特点和使用场景等方面对其...

    contains 和 Dictionary学习

    var value:Object = dictionary[key]; dictionary[key] = newValue; ``` `Dictionary` 还有一些需要注意的特性: 1. `Dictionary` 不会自动管理键的引用,如果键的对象被销毁,对应的条目也不会自动删除。 2. 由于...

    dotnet C# 字典 Dictionary 和 Hashtable 的性能对比.rar

    本篇文章将深入探讨`Dictionary`和`Hashtable`的区别以及在C#开发中的应用。 首先,`Dictionary, TValue&gt;`是C#标准库中的一个泛型类,自.NET Framework 2.0起引入。它的主要优点在于类型安全性,因为键和值都是强...

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

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

    C#实现json格式转换成对象并更换key的方法

    在这个示例中,我们首先使用`JavaScriptSerializer`将JSON字符串转换为`Dictionary, object&gt;`,然后遍历这个字典,对每个键执行转换操作,并将转换后的键和对应的值放入新的字典`resultDict`中。`ConvertKey`方法...

    ABAP Dictionary

    7. 业务对象和业务数据类型:ABAP字典支持面向对象的概念,如业务对象(Business Object)和业务数据类型(Business Data Type),它们用于更复杂的业务逻辑和数据模型。 8. 与ABAP代码的交互:ABAP字典中的对象...

    C#中Dynamic和Dictionary性能比较

    在C#编程中,`dynamic`和`Dictionary, TValue&gt;`是两种常见的处理动态数据的方式。它们各有优缺点,适用于不同的场景。这篇文章主要探讨了两者在性能方面的差异,以帮助开发者在实际应用中做出合适的选择。 首先,`...

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

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

    Tool for Flatten A Folder

    标题“Tool for Flatten A Folder”指的是一个用于整理和扁平化文件夹结构的命令行工具。这个工具的主要功能是帮助用户将多个不同目录下的特定文件复制到一个单一的目标目录中,从而实现文件夹的扁平化,使得文件...

Global site tag (gtag.js) - Google Analytics