日期:2014-05-16  浏览次数:20364 次

JS内部的字典形式
JavaScript内部的数据组织形式用了太多的字典形式,对象可以用字典的形式来组织,甚至数组也是字典的形式,特意强调数组是因为数据不仅可以用数字作为下标,用字符串也可以作为下标
var stack = new Array();
stack["first"] = 3;
stack["second"] = "second";
stack["third"]  = new Date();


甚至在JavaScript中,数字下标会最终被转化为字符串形式的下标
同是,看出了不同类型的数据时可以组织到同一个数组中的

对于以字符串为下标的数组,访问其中的元素和遍历一般JSON形式对象的方式一样:
for(var item in stack){//也就是访问Map键
alert(stack[item]);
}
//////////////分割/////////////////////

上面的有些理论是错误的,下面:

我们已经提到过,对象是无序数据的集合,而数组则是有序数据的集合,数组中的数据(元素)通过索引(从0开始)来访问,
数组中的数据可以是任何的数据类型.数组本身仍旧是对象,但是由于数组的很多特性,通常情况下把数组和对象区别
开来分别对待(Throughout this book, objects and arrays are often treated as distinct datatypes.
This is a useful and reasonable simplification; you can treat objects and arrays as separate types
for most of your JavaScript programming.To fully understand the behavior of objects and arrays,
however, you have to know the truth: an array is nothing more than an object with a thin layer of extra
functionality. You can see this with the typeof operator: applied to an array value, it returns
the string "object".  --section7.5).
创建数组可以用"[]"操作符,或者是用Array()构造函数来new一个.


通过上面的解释,我们已经知道,对象的属性值是通过属性的名字(字符串类型)来获取,而数组的元素是通过索
引(整数型 0~~2**32-1)来得到值.数组本身也是一个对象,所以对象属性的操作也完全适合于数组.

Js代码 
var array = new Array("no1","no2");   
array["po"] = "props1";   
alert(array.length);   //2  说明字符串不是下标,而是数组对象的属性 
//对于数组来说,array[0]同array["0"]效果是一样的(?不确定,测试时如此)   
alert(array[0] + "_" + array["1"] + "_" + array.po);//no1_no2_props1 






///记录一个Array的方法sort
sort不带参数,是默认按字母顺序排序
sort带上参数,就是按照参数提供的比较器来排序,这点和java的集合框架的排序又很大的相似性,java的Collections.sort() 也提供了两种显示的参数列表,带比较器的和不带比较器的,不带比较器就按照自然顺序来排序。
static <T extends Comparable<? super T>> 
void 
 sort(List<T> list) 
          根据元素的自然顺序 对指定列表按升序进行排序。 
static <T> void 
 sort(List<T> list, Comparator<? super T> c) 
          根据指定比较器产生的顺序对指定列表进行排序。 


至于js中怎么组织这个代码,见下面的实例:
function comparator(a,b){
   return a-b;
}
var array = [10, 23, 44, 58, 106, 235];   
array.sort(sorter);   
print(array);